by Dinesh Thakur Category: Structure And Union

As we already know, a structure is an ordered list of elements of either the same or different types. A union is similar to a structure but with one major difference that the structure stores all its members one after another, whereas the union can store only one member at a time, since all the members in a union are stored beginning from the same memory location. Thus, the total memory required to store a union is the same as that required for the largest member in it. The union is useful when we have to store one of the alternative values of different types and yet conserve space.

Illustrates working of a union.

#include<stdio.h>

union Student
{
 float Grades ;
 int Reg_number;
};
void main ()
{
   union Student S1;
   clrscr();
   S1.Grades = 75.5;
   S1.Reg_number = 20090001;
   printf("Data of S1 is:");
   printf("\nReg_number =%d", S1.Reg_number);
   printf("\nGrades= %f\n", S1.Grades);
   printf("Address of Reg_number= %x\n", & S1.Reg_number);
   printf ("Address of Grades= %x\n", & S1.Grades);
}
Union in c


About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.