Structure Unions in C Programming
Unions
- A union is similar to a structure.
- The only difference between a union and structure is that information can be stored in one field at any one time.
- They are used for saving the memory.
- Unions can be used for applications which involve a lot of multiple members, where the values need not be assigned to all the members at one time.
Syntax
union union_name
{
member 1;
member 2;
.
.
member n;
};
The individual union variables are declared as
storage-class union union_name var1, var2, …..varn;
The combination is given as
storage-class union union_name
{
member 1;
member 2;
.
.
member n;
}var1, var2, …..varn ;
The members are accessed in the same way as the structure members are i.e. by using the
'.' or '→' operator.
Syntax:
union_name.member
OR
union_name → member
Example : Demonstration of a simple union
#include <stdio.h>
union student
{
int roll_no;
float fees;
};
void main()
{
union student data;
data.roll_no = 5;
printf( "data.roll_no : %d\n", data.roll_no);
data.fees = 500.50;
printf( "data.fees : %f\n", data.fees);
}
Output:
data.roll_no : 5
data.fees : 500.500000
- Just like structures we can have nested unions, arrays of unions and pointer to union.
- The pointers can be passed to and from the functions.
- Unions are initialized with only one value and value of the first type.
- The operations performed on unions can be the same as structures.