Union in C


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;

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 26-Jun-2020

533 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements