Unions
In the past we've looked at structs. To remind you a struct is a way of managing several variables in one complete "super" variable which can be assigned or copied in one statement. The definition and use of a struct is thisstruct s {Download Example 5.
int a;
char * b;
int c[10];
};
typedef struct s sblock; // avoids needing the word struct!
sblock sval; // declare an instance
sval.c[4] =10; // assign a value
In a struct like the type s above, the three fields, a b and c are laid out in memory one after another. In a union though, all three fields occupy the same space.
If you know Borland/Turbo Pascal or Delphi then you may know of a variant record (nothing to do with Variant types). This is similar.
Unions are a bit of an oddity- not something you will use in everyday programming but when you need them, they are handy. Syntactically, take a struct and replace the word with union. That's it!
union u {Within the union u all declared fields start at the same location and the size allocated is big enough to take the largest field. The array c is ten times the size of the int a or the char * b so the structure has to big enough to take it. If the ints are 32 bits then sizeof(u) will be 40 bytes, as big as c. In any variable of type union u, assigning a value to a is the same as assigning it to b or c[0]. The space occupied by c[1] to c[9] is inaccessible and thus wasted space as far as a and b are concerned.
int a;
char * b;
nt c[10];
};
On the next page - Uses of unions

