| Union |
| |
| Introduction |
| |
| Union are derived data types, the way structure are. Though, unions and structures look alike, and there is a fundamental difference. |
| |
| While structure enables you to create a number of different variables stored in difference places in memory, unions enable you to treat the same space as a number of different variables |
| |
| Union-Definition and Declaration |
| |
| Unions, like structures, contain members whose individual data types may differ from one another. |
| |
| However, the members within a union all share the some storage space within the computer's memory, whereas each member within a structure is assigned its own unique storage area. |
| |
| Thus, unions are used to conserve memory. |
| |
| They are useful for applications involving multiple members, where values need not be assigned to all of the members at any one time. |
| |
| Within a union, the bookkeeping required to store members whose data types are different (having different memory requirements) is handled automatically to the compiler. |
| |
| However, the user must keep track of what type of information is stored at any given time. |
| |
| An attempt to access the wrong type of information will produce meaningless results. In general terms, the composition of a union may be defined as: |
| |
| Union tag |
| { |
| Member 1; |
| Member 2; |
| ….. |
| member n; |
| }; |
| |
| Where union is required keyword and the other terms have the same meaning as in a structure definition. |
| |
| Individual union variables can then be declared as: |
| storage-class union tag variable 1, variable 2, . . . , variable n; |
| |
| Where storage-class is an optional storage class specified, union is a required keyword, tag is the name that appears in the union definition, and variable 1, variable 2, . . . , variable n are union. |
| |
| The two declarations may be combined, just as we did with structures. Thus, we can write Storage-class union tag |
| |
| { |
| Member 1; |
| Member 2; |
| . . . . . |
| member n; |
| } |
| |
| The tag is optional in this type of declaration. |
| |
| Notice that the union and structure declarations are external to the program functions, but the structure variable is defined locally within each function. |
| |
| |
| |
| |
| |