What is Union C

  • What is a union
  • Using unions

Let us now turn our attention to unions which are very much similar to structures where both are used to group number of different variable elements. We will study what are unions how they are different from structures and how they are used.

What is Union
The composition of union may be defined as

This is similar to structure. The only difference being the keyword ‘union’ instead of ‘struct’. Individual union variables can be declared as

storage-class union tag var1, var2, ………varn;

The combination gives

The tag is optional here. The members of union are accessed in the same way as structure members are accessed, using the ‘.’

operator or ->operator

The difference between structure and union lies in the functionality and hence the purpose of using them. If we have a structure

A total of 12 bytes for character array and 2 bytes for integer =14 bytes would be allocated to above structure. Any member of the structure can be accessed at any time. A union is used for application involving multiple members where values of only one member need to be used at any one time. If we need a value of either size or color at a time but never both at a time, unions are used. Eg A shirt is to be identified by either size or color.

The space allocated to any union is large enough to hold largest of all types. Here 12 bytes, since char array is largest of the two given types. The same 12 bytes are used by the char array as well as integer, thus saving space. Well the programmer has to keep track of which union member is currently being used at any step.

Using unions
A simple program using unions follows;

output :
space assigned to union = 4 bytes.
cost = 500.799 size = 26711
cost = 00.0000 size = 12

We have defined a union and a structure, one of whose member is union id. First we have found out the memory space allocated to the union using the size function. It is seen from the output that 4 bytes are allocated to union, since cost variable is of 4 bytes. Then value is assigned to cost, member of union. From the output it is seen that at that time ‘size’ contains no reasonable value.

Just like nested structures, we can have nested unions and union in structures (as in previous example). Also arrays of unions and pointer to union can be used. Pointer to union can be passed to and from functions. Unions can be initialized but with only one value. The operations performed on unions are same as on structures like accessing union members, taking address, assignment of entire union variable to other union variable.

Face Book Twitter Google Plus Instagram Youtube Linkedin Myspace Pinterest Soundcloud Wikipedia

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

C Topics