Best Industrial Training in C,C++,PHP,Dot Net,Java in Jalandhar

Thursday 4 April 2013

Unions in C Language

Union :
Union is user defined data type used to stored data under unique variable name at single memory location.
Union is similar to that of stucture. Syntax of union is similar to stucture. 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 :
    
  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.
Creation Date : 10 Nov 2010 09:24:09 PM
Author :Abhejeet Singh*/
#include <stdio.h>
#include <conio.h>
union techno
{
 int id;
 char nm[50];
}tch;

void main()
{
 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();
}

Output :

 Enter developer id : 101

 Enter developer name : technowell

Developer ID : 25972
Developed By : technowell_

No comments:

Post a Comment