Image

C Language - Union - Union

Union

Union is just similar to structure it is also used to create user define datatype. Like structures, unions are also a group of a number of variables. However, member variables do not have separate spaces allocated for them.

A single space in the memory corresponding to the largest member variable is assigned to a union. As a result a union type data stores a single value which can be accessed by referencing individual members of the union.

Interpretation of the value stored in a union depends on the variable which is used to access the stored value. Union type data are particularly useful when space in the memory is at premium.

Syntax:
		union
		{
data_type_1 variable_name_1;
data_type_2 variable_name_2;
…
data_type_n variable_name_n; };

Example

union abc { int a1; char a2; float a3; }; union abc union1;

WAP to compare memory on struct and union

#include<stdio.h>
#include<conio.h>
main(){
struct stag
{
 char c;
 int i;
 float f;
  };
union utag
{
 char c;
 int i;
 float f;
  };

 union utag uvar;
 struct stag svar;
	clrscr();
	printf("size of svar = %u ",sizeof(svar));
	printf("address of svar = %u",&svar);
	printf("address of member : %u %u %u",&svar.c,&svar.i,&svar.f);
	printf("size of uvar = %u ",sizeof(uvar));
	printf("address of uvar = %u",&uvar);
	printf("address of member : %u %u %u",&uvar.c,&uvar.i,&uvar.f);
 getch();
}
Output
size of svar = 7
address of svar = 65514
address of member = 65514 65515 65517
size of uvar = 4
address of uvar 65522
address of member = 65522 65522 65522