6.11. Data Structures
To this point in the chapter, you have dealt with only simple data types such as int, float, and char. C was one of the first languages to facilitate structured programming, part of which entails creating more complex data relationships than you have seen so far. C provides a number of constructions to group data together, and this section introduces you to them.
Sometimes it is necessary to represent variables that can take only a few discrete values. For example, a variable representing the type of a pet could be represented by an integer restricted to a small range of values. Such a variable is referred to as an enumerated type. C provides the enum data type to represent enumerated types. Consider this example:
typedef enum { DOG, CAT, BIRD } Pet;
Pet myPet = CAT;
switch (myPet) {
case DOG:
printf("I have a dog!\n");
break;
case CAT:
printf("I have a cat!\n");
break;
case BIRD:
printf("I have a bird!\n");
break;
default:
printf("I have an undefined beast\n");
}
The keyword typedef is used in conjunction with the keyword enum to define a new type called Pet. This type can take three meaningful values: DOG, CAT, and BIRD. A variable called myPet is then declared to be of the type Pet, and is initialized to CAT. A switch statement checks the type of myPet, printing a message depending on its value.
C simply represents enumerated types as integers, so they can be used anywhere an int can be used. For example, you can subscript an array with an enum:
int averagePetLifetime[3]; ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access