Thursday, July 14, 2011

UNION

UNION

Union

Union is used to group a number of different variables together which enables us to treat the same space in memory as a number of different variables. Union and structure are exactly alike, the only difference is that structure uses different memory space to store different variables but union uses the same memory space to store different variable.

Syntax:

union structure_name
{
Data_type member;
........
};
union structure_name  structure_variable;

Declaring Union

A union is declared by using the keyword union followed by an optional union tag followed by the body of the union. The variables or members of the union are declared within the body. Here is an example of a union that would be useful in representing the book containing id, name of book and price.
union book {
   int id;
   char name[25];
    float price;
};
The union declaration is a user defined data type. Variables of type book may be declared similarly to the way variables of a built in type are declared.
union book b1, b2, b[100];
Example:
#include<stdio.h>
#include<conio.h>
 
void main()
{
    union try
    {
          int i;
          char ch[2];
    };
   
    union try t;
   
    t.ch[0]=50;
    t.ch[1]=30;
    t.i=512;
 
    printf("t.i=%d\n",t.i);
    printf("t.ch[0]=%d\n",t.ch[0]);
    printf("t.ch[1]=%d",t.ch[1]);
}
Output:
t.i = 512
t.ch[0] = 0
t.ch[1] = 2
Reason:
Values of t.ch[0] and t.ch[1] i.e. 50 and 30 , is changed to 0 and 2 respectively after t.i is assigned with 512. This happens because t.ch[0] and t.ch[1] share the same memory.

0 comments:

Post a Comment