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]; ...

Get Beginning Mac OS® X Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.