Thursday, April 7, 2016

Union



  • Unions are C variables whose syntax look similar to structures, but act in a completely different manner. 


  • Once a union variable has been declared, the amount of memory reserved is just enough to be able to represent the largest member. (Unlike a structure where memory is reserved for all members). 

  • Data actually stored in a union’s memory can be the data associated with any of its members. 

  • But only one member of a union can contain valid data at a given point in the program. 

  • It is the user’s responsibility to keep track of which type of data has most recently been stored in the union variable. 




Example :


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
#include <stdio.h>
#include <string.h>

 union Data{
int i;
float f;
char str[20];
};
int main( ){
union Data d1;
d1.i = 10;
d1.f = 220.5;
strcpy(d1.str,"Embedded C");
printf( "d1.i : %d\n", d1.i);
printf( "d1.f : %f\n", d1.f);
printf( "d1.str : %s\n", d1.str);
printf("Union size : %d199 bytes",sizeof(d1));
return 0;
}


Output :

d1.i : 1700949317
d1.f : 66829405762910173528064.000000
d1.str : Embedded C

Share this

0 Comment to "Union"

Post a Comment