Join Regular Classroom : Visit ClassroomTech

Unions in C

A union is a user defined datatype that also like structure allows to store different datatypes but in union it stores in similar location. In union one member can contain only one value at a time. So, the size of union will be lesser than the size of structure. So, union is more efficient where we needn’t to store multiple members at a same time.

Remember:
1. The size of union will be as per the size of the highest member size.
2. To define union we need union keyword.

Let us observe the following example:

/* C programs to understand how union works */
/* www.codewindow.in */
#include <stdio.h>
union test {    // Syntax for Declaration of an Union
	int a, b;
}; 
int main() { 
	union test s;	// A union variable s
	s.a = 4;   // s.b also gets value 4
	printf("After making a = 4:n a = %d, b = %dnn",s.a, s.b);
 	s.b = 6;    // s.a is also updated to 6 
	printf("After making b = 6:n a = %d, b = %dnn",s.a, s.b); 
 	return 0;
} 

Output:

After making a = 4:
a = 4, b = 4
After making b = 6:
a = 6, b = 6


You Missed

Also Checkout