Unions

Union is a concept borrowed from structures and therefore follows the same syntax as structure. However, there is a major distinction between them in terms of memory storage. In structure, each member or element has its own memory location Whereas all the members of the union use the same memory location.Like structure,a union can be declared using the keyword Union as follow:-

For example:-

After defining a union format we can declare variable of that type.A union variable declaration is same as declaration of structure variable .A general form is:-

union union_name variable_name;
For example:-

The compiler allocates a piece of memory that is large enough to hold that largest variable type in the union. In the declaration above, the member c(float) is the largest among the member/So all three variables shares the same address. For access the union member, we can use the same syntax that we use for structure members. for example:-

Note:- Union creates a memory location that can be used by any one of its members at a time.When a different member is assigned a new value supersedes the previous member value.

C Code Example