Offers
Thanks for visiting www.technoexam.com. Stay connected with us for more latest programming updates...

You are here : Home >> Tutorials >> C

Go
Basic C Tutorial

Contents
What is C ?
History
Structure of C Program
Variables & Keywords
Constants
Data Types
Operators
Operators Precedence
Conditional Statements
if Statement
if else Statement
nested if else
switch case
Looping Statements
While loop
Do While loop
For loop
Break
Continue
Goto
Functions
Passing Value
Returning Value
Passing & Returning
Recursion
Storage Class
Array
Structure
Pointer
Union
Strings
Header File
Programs Library
Projects Library
Learn More+

Contact Us

+91-8806583119

Union in C

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.

Syntax:

	union union_name
	{
		<data-type> element 1;
		<data-type> element 2;
		<data-type> element 3;
	}union_variable;

Example:

	union techno
	{
		int comp_id;
		char nm;
		float sal;
	}tch;
	

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.

Memory Allocation Of Union

	    C union
	 Fig : Memory allocation for union

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

	tch.comp_id
	tch.nm
	tch.sal

Program :

// Program to demonstrate union.
#include <stdio.h>
#include <conio.h>

union techno
{
	int id;
	char nm[50];
}tch;


int main(void)
{
	clrscr();
	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);
	getch();
	return 0;
}

Output :


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

Developed By : technowell_

Download PDF
Published on: 12th Nov 2010, Last Updated on: 18th Dec 2014

Mr. Dinesh Kudache
AUTHOR: Mr. Dinesh Kudache

Mr. Dinesh is the Founder and CEO of technoexam.com. He had 6+ years experience in Application Programming, System Programming, Web Design and Development, Google Expertise. He had written 5000+ various articles on programming. Browse more articles by this author.

Link this post on your Blog/Website :