Union


Just like structures, unions are used to create user-defined types. A union is a collection of one or more variables, possibly of different types. All the major aspects of union, like defining a union type, declaring objects of a union type, using and performing operations on objects of a union type are the same as that of structures. The only difference between them is in the terms of storage of their members. In structures, a separate memory is allocated to each member, while in unions, all the members of an object share the same memory.
A union object is used only if one of its constituting members is to be used at a time. In such a situation, it proves to be memory efficient as compared to structures. 

Practical Application of Unions

In the previous chapters, you have used printfscanfgetch and other library functions a number of times. These library functions perform rudimentary operations like printing an output on the screen, reading input from the keyboard, etc. In other words, these functions interact with the hardware of the machine. However, if you delve deeper into the technical details of how these functions interact with the hardware, you will come to know that these functions do not have any direct interaction with the hardware. The process through which the library functions interact with the hardware of the machine is shown in Figure 5.
Figure 5. Hardware interaction


Post a Comment

Previous Post Next Post