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;
* Memory Allocation :
Fig : Memory allocation for union
tch.comp_id tch.nm tch.sal
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]; }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_
0 comments:
Post a Comment
Dont Forget for Commets