Union in C

CProgrammingServer Side Programming

Union is a user defined datatype. All the members of union share same memory location. Size of union is decided by the size of largest member of union. If you want to use same memory location for two or more members, union is the best for that.

Unions are similar to the structure. Union variables are created in same manner as structure variables. The keyword “union” is used to define unions in C language.

Here is the syntax of unions in C language,

union union_name {
   member definition;
} union_variables;

Here,

union_name − Any name given to the union.

member definition − Set of member variables.

union_variable − This is the object of union.

Here is an example of unions in C language,

Example

 Live Demo

#include <stdio.h>
#include <string.h>
union Data {
   int i;
   float f;
}data, data1;
int main( ) {
   printf( "Memory size occupied by data : %d\t%d", sizeof(data), sizeof(data1));
   return 0;
}

Output

Memory size occupied by data : 44

In the above program, a union Data is created with the objects of union.

union Data {
   int i;
   float f;
}data, data1;
raja
Published on 05-Nov-2018 10:32:09
Advertisements