Write a short note on Unions?


Unions are a concept borrowed from structures and therefore follow the same syntax as structures.

However, there is major distinction between them in terms of storage. In structures, each member has its own storage location. Whereas all the members of a union use the same location.

This implies that, although a union may contain many members of different types. It can handle only one member at a time. Like structures, a union can be declared using the keyword union as follows.

union item
{
int m;
float x;
char c;
}
code;

This declares a variable code of type union item. The union contains 3 members each with a different data.

However, we can use only one of them at a time. This is due to the fact that only one location is allowed for a union vars. Irrespective of its size.


The compiler allocates a piece of storage that is large enough to hold the largest variable type in the union. In the above example the member x requires 4 bytes which is the largest among the members. The above figure shows how all the 3 variables share the same address.

To access a union member, we can use the same sy that we use for structure members . ie.

code. m
                       
code. x
                                   
code .c

Are all valid member variables. During accessing we should make sure that we are accessing the member whose value is currently stored. Union may be used in all places where a structure is allowed.


Related

C Language 4794829217638334447

Post a Comment

emo-but-icon

item