twitter
    Find out what I'm doing, Follow Me :)

What Are Unions?

Load the file named union1.c for an example of a union. Simply stated, a union allows you a way to look at the same data with different types, or to use the same data with different names. Examine the program on your monitor.

main( )
{
union {
short int value; /* This is the first part of the union */
/* This has to be a short with the HI-TECH */
/* C Compiler due to the int being 32 bits */
struct {
char first; /* These two values are the second */
Structures and Unions C Tutorial 11-6
char second;
} half;
} number;
long index;
for (index = 12;index < 300000;index += 35231) {
number.value = index;
printf("%8x %6x %6x\n",number.value,number[half]first,
number[half]second);
}
}


In this example
we have two elements to the union, the first part being the integer named "value", which is stored as a two byte variable somewhere in the computers memory. The second element is made up of two character variables named "first" and "second". These two variables are stored in the same storage locations that "value" is stored in, because that is what a union does. A union allows you to store different types of data in the same physical storage locations. In this case, you could put an integer number in "value", then retrieve it in its two halves by getting each half using the two names "first" and "second". This technique is often used to pack data bytes together when you are,  
for example, combining bytes to be used in the registers of the microprocessor.

Accessing the fields of the union are very similar to accessing the fields of a structure and will be left to you to determine by studying the example. One additional note must be given here about the program. When it is run using most compilers, the data will be displayed with two leading f’s due to the hexadecimal output promoting the char type variables to int and extending the sign bit to the left. Converting the char type data fields to int type fields prior to display should remove the leading f’s from your display. This will involve defining two new int type variables and assigning the char type variables to them. This will be left as an exercise for you. Note that the same problem will come up in a few of the later files also.

When using the HiTech C compiler, data will be displayed with more than two leading ‘f’s, due to the use of the short int value.

Compile and run this program and observe that the data is read out as an "int" and as two "char" variables. The "char" variables are reversed in order because of the way an "int" variable is stored internally in your computer. Don’t worry about this. It is not a problem but it can be a very interesting area of study if you are so inclined. The ‘char’ variables are in their correct position when compiled with HiTech C.