#define NAMELENGTH 20 #include #include typedef char name_t[NAMELENGTH]; typedef enum {FALSE=0, TRUE} boolean; typedef enum {DOG=7, FISH=1, CAT} pet_kind; typedef struct { int age; name_t name; float weight; int num_bones; } dog; typedef struct { name_t color; boolean salt_water; } fish; typedef struct { int age; name_t name; float weight; } cat; typedef struct { pet_kind kind; union { dog mydog; fish myfish; cat mycat; } info; } pet; int main () { pet rover; rover.kind = DOG; rover.info.mydog.age = 9; strcpy (rover.info.mydog.name, "J.D.'s Beach Bum II"); rover.info.mydog.num_bones = 4; rover.info.myfish.salt_water = TRUE; /* still legal, but changes the dog's name! */ switch (rover.kind) { case (DOG) : { printf ("%s has %d bones.", rover.info.mydog.name, rover.info.mydog.num_bones); break; } case (FISH) : { printf ("Rover is %s", rover.info.myfish.color); break; } case (CAT) : { printf ("Rover is %d years old.", rover.info.mycat.age); break; } } /* rover.mycat.num_bones = 5; doesn't compile */ rover.kind = TRUE; /* presto-change-o, rover is now a fish! */ /* because the numeric value of TRUE happens to equal that of FISH */ return 0; }