Unions

Union is a concept borrowed from structures and therefore follows the same syntax as structure. However, there is a major distinction between them in terms of memory storage. In structure, each member or element has its own memory location Whereas all the members of the union use the same memory location.Like structure,a union can be declared using the keyword Union as follow:-

	union union_name
	{
	 data_type member1;
	 data_type member2;
	 --------- --------
	 --------- --------
	};
	 

For example:-

	
	union data
		{
			char a;
			int  b;
			float c;
		};

After defining a union format we can declare variable of that type.A union variable declaration is same as declaration of structure variable .A general form is:-

union union_name variable_name;

For example:-

	union data
		{
			char a;
			int  b;
			float c;
		};
		union data d1;

The compiler allocates a piece of memory that is large enough to hold that largest variable type in the union. In the declaration above, the member c(float) is the largest among the member/So all three variables shares the same address. For access the union member, we can use the same syntax that we use for structure members. for example:-

		d1.a
		d1.b
		d1.c

Note:- Union creates a memory location that can be used by any one of its members at a time.When a different member is assigned a new value supersedes the previous member value.

C Code Example

#include <stdio.h>
union data
		{
			char a;
			int  b;
			float c;
		};
		union data d1;
		
void main()
{	
printf("Enter value ");
scanf("%c",&d1.a );

printf("\n Enter value is %c",d1.a);

}