Programming in C

(Barry) #1
Working with Unions 377

float f;
char c;
} data;
} table [kTableEntries];


sets up an array called table, consisting of kTableEntrieselements. Each element of
the array contains a structure consisting of a character pointer called name, an enumera-
tion member called type, and a union member called data. Each datamember of the
array can contain either an int,a float, or a char.The member typemight be used to
keep track of the type of value stored in the member data.For example, you could
assign it the value INTEGERif it contained an int,FLOATINGif it contained a float, and
CHARACTERif it contained a char.This information would enable you to know how to
reference the particular datamember of a particular array element.
To store the character '#'in table[5], and subsequently set the typefield to indi-
cate that a character is stored in that location, the following two statements could be
used:


table[5].data.c = '#';
table[5].type = CHARACTER;


When sequencing through the elements of table,you could determine the type of data
value stored in each element by setting up an appropriate series of test statements. For
example, the following loop would display each name and its associated value from
tableat the terminal:


enum symbolType { INTEGER, FLOATING, CHARACTER };


...

for ( j = 0; j < kTableEntries; ++j ) {
printf ("%s ", table[j].name);


switch ( table[j].type ) {
case INTEGER:
printf ("%i\n", table[j].data.i);
break;
case FLOATING:
printf ("%f\n", table[j].data.f);
break;
case CHARACTER:
printf ("%c\n", table[j].data.c);
break;
default:
printf ("Unknown type (%i), element %i\n", table[j].type, j );
break;
}
}

Free download pdf