Bharat Banate's Work Profile

View Bharat Banate's profile on LinkedIn

Thursday, June 19, 2008

C++: Anonymous unions and enums

An anonymous union does not have a union name (tag) and its elements can be accessed directly without using a union variable.
For example,

union {
int i;
char ch[2];
};

Both i and array ch[] share the same memory locations and can be accessed directly simply by saying

i = 10;
ch[0] = 'A';

Simply omitting the union name in declaration does not make the anonymous union. For an union to qualify as an anonymous union, the declaration must not declare a variable of the union type.

Similarly, we can build anonymous enums as shown below:

enum {first, second, third};
int position = second;

The stream I/O classes define several anonymous enumerated types.

0 comments: