Unions

Unions are similar to structures in appearance, but their meaning is quite different. A union is a compound data object whose different fields are of different types, only one of which is ever present at a given time. They are not simultaneously present as with a struct.

When the different field types of a union are of different sizes, then the size of the union is the maximum size of all of the types of fields (not the sum of the sizes).

The following union:

	union { /* a tag is optional as it is for struct */
		long b;
		float r;
	} word;

would allow us to assign word.r with a floating point value, and then to use word.b to have access to the individual bits with the bitwise operators of that floating point number. We could thus take the absolute value by doing a bitwise AND with a constant where the sign bit was zero and all the other bits were one.

One of the main uses for union's is to model things whose type of contents change with time - not because of labor-management problems. This happens frequently during simulations of a computer itself where the internal data type changes with the instruction being used.


© 1991-2008 Prem Sobel. All Rights Reserved.