The "down and dirty" of both the union and enum
A union, in almost all regards, is just like a structure. The difference is that all the members
of a union use the same memory area, so only one member can be used at a time. A union
might be used in an application where the program needs to work with two or more values
(of different data types), but only needs to use one of the values at a time. Unions conserve memory by storing all their members in the same memory location. Unions are declared just like structures, except the key word union is used instead of
struct . Here is an example:
1 2 3 4 5
|
union PaySource
{
short hours;
float sales;
};
| |
A union variable of the data type shown above can then be defined as PaySource employee1; The PaySource union variable defined here has two members: hours (a short ), and sales (a float ). The entire variable will only take up as much memory as the largest member (in this case, a float ).
Using the enum key word you can create your own data type and specify the values that
belong to that type. Such a type is known as an enumerated data type . Here is an example of an enumerated data type declaration:
enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY };
An enumerated type declaration begins with the key word enum , followed by the name of
the type, followed by a list of identifiers inside braces, and is terminated with a semicolon.
The example declaration creates an enumerated data type named Day . The identifiers
MONDAY , TUESDAY , WEDNESDAY , THURSDAY , and FRIDAY , which are listed inside the braces, are known as enumerators. So just what are these enumerators MONDAY , TUESDAY , WEDNESDAY , THURSDAY , and FRIDAY ? You can think of them as integer named constants. Internally, the compiler assigns integer values to the enumerators, beginning with 0. The enumerator MONDAY is stored in memory as the number 0, TUESDAY is stored in memory as the number 1, WEDNESDAY is stored in memory as the number 2, and so forth. To prove this, look at the following code:
1 2 3
|
cout << MONDAY << endl << TUESDAY << endl
<< WEDNESDAY << endl << THURSDAY << endl
<< FRIDAY << endl;
| |
The output will be: