In this tutorial, complex and user defined data types and enumerations are explored. Designed for beginner and intermediate programmers in the C and C++ languages.
The C programming language provides several basic types:
We can then use these to declare variables - places to store information - which can accommodate data of a specific type. On top of that, we can also define arrays - collections of pieces of data - to allow us to store multiple values under a single variable.
If this is not already familiar territory, the reader should consult:
These are also part of the Computer Programming Topic here at Suite101, and can help to fill in the gaps.
On top of these, C also allows us to create our own types - either as references to built-in types, or multipart types (like a record with fields) - depending on the data we want to model.
The first keyword we shall explore is typedef. With this keyword we can define a new type, and give it a user-friendly name. For example:
This code tells the compiler that we want to define a type Boolean, that is equivalent to an integer. In order to use this new type, we could use code similar to:
This is not, however, very user friendly, but can be made more so by using the #define keyword to define values for true and false:
This is fine, but there is en even more elegant way to achieve this.
An enumerated data type is a list of possible values, each of which is assigned a sequential number. This allows us to write code that can compare values easily. So, for our Boolean example:
This tells the compiler that we would like a Boolean type that evaluates to FALSE, or TURE. The compiler will assign the values 0 and 1 to these new types, enabling comparisons such as:
We can also define more complex lists:
However, in order to define complex data types which can contain data beyond the basic types, we need two more keywords.
The struct keyword allows us to create record style data. For example, if we need to define a new data type to store names, we might create it with:
So, we can now declare a variable of type sName, and store various values in it:
Of course, we could also combine the above with enumerated types for the static list of values Mr, Mrs, Miss etc. but we'll leave that as a reader exercise for now.
The final keyword that we can use to create user defined types is the untion keyword. This permits us to create a type which can hold multiple values, but only one at a time.
So, if we wanted to create a type to hold either integers or floating point numbers, we would write:
We can then set either a or b, but not both at the same time, using the regular assignment operator:
And... we're done. Questions can be asked through the message board below; so, let's interact!