Union in C Programming

Union is user defined data type used to stored data under unique variable name at single memory location.

Union is similar to that of structure. Syntax of union is similar to structure. But the major difference between structure and union is ‘storage.’ In structures, each member has its own storage location, whereas all the members of union use the same location. Union contains many members of different types, it can handle only one member at a time.

To declare union data type, ‘union’ keyword is used.

Union holds value for one data type which requires larger storage among their members.


	union union_name
		 element 1;
		 element 2;
		 element 3;


	union techno
		int comp_id;
		char nm;
		float sal;

In above example, it declares tch variable of type union. The union contains three members as data type of int, char, float. We can use only one of them at a time.


Fig : Memory allocation for union

To access union members, we can use the following syntax.


Program :

/*  Program to demonstrate union.
Creation Date : 10 Nov 2010 09:24:09 PM
Author :www.technoexam.com [Technowell, Sangli] */

#include <stdio.h>
#include <conio.h>

union techno
	int id;
	char nm[50];

int main(void)
	printf("\n\t Enter developer id : ");
	scanf("%d", &tch.id);
	printf("\n\n\t Enter developer name : ");
	scanf("%s", tch.nm);
	printf("\n\n Developer ID : %d", tch.id);//Garbage 
	printf("\n\n Developed By : %s", tch.nm);
	return 0;

Output :
	Enter developer id : 101
	Enter developer name : technowell
Developer ID : 25972

Developed By : technowell_

Leave A Comment

Your email address will not be published. Required fields are marked *