-->

Unions in C

Unions in C
Unions
·         Unions concept and syntax is the same as structures.
·         There is a difference between structure and union in terms of storage.
·         In the structure, each member has its own storage location, where as all the members of the union use the same location.
·         A union may contain many members of different types, it can handle only one member at a time.
·         Like the 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 three members, each with a different data type.
·         We can use only one of them at a time.
·         This is due to the fact that only one location is allocated for a union variable, irrespective of its size.
Example:
The member 'x' in the union 'code'
·         The figure shows how all the three variables share the same address.
·         This assumes that a float variable requires 4 bytes of storage.

·         To access union members, we can use the same syntax that we use for structure members, i.e.
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.
Example:
code. m=189;
code.x=759.36;
printf("%d", code.m);
would produce inaccurate ouput (machine dependent)
·         Only one member uses the memory allocated in a union variable.
·         When a different member is assigned a new value, the new value takes the place of a previous member value.
·         Unions are used in all places where the structure is allowed.
·         Unions may be initialized when the variable is declared. But unlike structures, it can be initialized only with a value of the same type as the first union member.
Example:
union item abc={100}; // valid
union item abc={10.75}; // invalid.
·         This is because the type of the first member is int.
·         Other members can be initialized by either assigning values or reading from the console.

Related Posts

Subscribe Our Newsletter