Union is similar to structures. The keyword used is "
union". It is used mainly to save the memory space and to store the values dynamically. The differences between union and structure is,
- Structure allocates memory for every member of it separately. Union allocates a single shared storage space for all its members which is the size of its biggest data member.
- In Structures, manipulations made on one member does not effect the other. In Union, since only single member is allocated at a time, manipulations done on one member reflects the other.
Syntax will be as follows:
union union_name
{
//declarations and initialization of members;
};
Accessing : The union variable can be retrieved in the same manner as in the structure. To access the union variable
. dot operator is used and to get the address of union variable
* is used. The union members can be accessed only one at a time. Unions are not much used when compared to structures as they does not store all the variables at a time.[/post_flow_steps_user_def]
Declaring : Union can be declared with the keyword union enclosed in
{} followed by
;
union example
{
char c;
int a;
float b;
} ex;
Initializing : The values are initialized with the datatypes inside the braces and the union members attached to the union with
. operator.
union example
{
char c;
int a;
float b;
} ex;
ex.c;
ex.a;
ex.b;