|Lessons||Lesson 40: Unions|
The syntax is similar as that of structure. In structures, we have different data members and all of these have their own memory space. In union, the memory location is same while the first data member is one name for that memory location. However, the 2nd data member is another name for the same location and so on.
Consider the above union (i.e. intOrChar) that contains an integer and a character as data members. What will be the size of this union? The answer is very simple. The union will be allocated the memory equal to that of the largest size data member. If the int occupies four bytes on our system and char occupies one byte, the union intOrChar will occupy four bytes. Consider another example:
The above union has two data members i.e. ival of type int and dval of type double. We know that double occupies more memory space than integer. Therefore, the union will occupy the memory space equivalent to double. The data members of unions are accessed in a similar way as we use with structures i.e. using the dot operator. For example:
To get the output of the data members, cout can be used as:
cout << “ The value in ival = “ << uval.ival;
It will print “The value in ival = 10”. Now what will be output of the following statement?
cout << “ The value in dval = “ << uval.dval;
We don’t know. The reason is that in the eight bytes of double, integer is written somewhere. When we use integer, it is printed fine. When we printed the double, the value of int will not be displayed. Rather something else will be printed. Similarly in the following statement i.e.
uval.dval = 100.0;
It will print the right value of dval. The value of this double is written in such a way that it will not be interpreted by the integer. If we try to print out ival, it will not display 100. Unions are little bit safer for integer and characters. But we have to think in terms that where to store the value in memory. Unions are very rarely used.
Our C / C++ tutorial ends here. How did you find it? Please let us know at email@example.com | Tutorial author: firstname.lastname@example.org