Skip to content

Type declaration

Type declarations allow you to create types. Programming languages offer a range of different code structures you can use to build your types.

Figure x.y: You can declare your own Data Types

You can declare your own Data Types

Type - Why, When, and How

Modelling types helps you see the different things that are within your program. When thinking about your data, you need to determine which kind of type you will create.

Most entities in your program will be structured data (structs in C/C++). Using structured data, you can create a type that contains a list of fields where each field contains a value. In this way you can capture all the data associated with the entity in a single value in your code. For example, a bank account could be made up of the account number, name, balance, and kind. All of this data can be captured in an account struct, allowing you to declare and work with account variables in your code.

At other times, you will want to capture data where a value needs to be restricted to a list of options. For example, the account kind in our bank account should be either a savings account, credit account, loan account, etc. In these cases you can create an enumeration to capture these options. This then means you can see these options within your code.

Very rarely, you want to be able to have a variable where it can store different types under different conditions. For example, you may have a variable that needs to be an integer sometimes, a double at other times, and an account at other times. In these cases you can use a union.

As you model your data you need to use these different type options to structure your solutions. When you think about your program, try to see how these different types could come together to structure your data in a way that will make it easy to code your functions and procedures. Ideally your data model will capture aspects from your program’s domain, making it easy to connect the types in your digital reality with the concepts within the domain.

In C/C++

Example

The following C code shows an example that creates an integer type that is an alias of int. We can use this anywhere we would have used int previously. Generally you would not do this, but it does show how this syntax works.

// Access our utilities like read_integer
#include "utilities.h"
// Create an integer type, that is an alias of int
typedef int integer;
integer main()
{
integer x;
x = read_integer("Enter a whole number: ");
return 0;
}

In C++ we can achieve the same thing with using to create an alias.

// Access our utilities like read_integer
#include "utilities.h"
// Create an integer type, that is an alias of int
using integer = int;
integer main()
{
integer x;
x = read_integer("");
return 0;
}

In most cases we will use the C version, as this works both for C and C++.