C examples for Data Type:union
The union type is like the struct type, except that all fields share the same memory position.
The size of a union is the size of the largest field it contains.
In the following code creates a union type, which is 4 bytes large.
union mix { char c; /* 1 byte */ short s; /* 2 bytes */ int i; /* 4 bytes */ };
Since the memory is sharing, the union type can only store one value at a time.
Changing one field will overwrite the value of the others.
#include <stdio.h> union mix {// w w w. j ava2 s .co m char c; /* 1 byte */ short s; /* 2 bytes */ int i; /* 4 bytes */ }; int main(void) { union mix m; printf("%d\n",m.c); printf("%d\n",m.s); m.c = 0xFF; /* set first 8 bits */ printf("%d\n",m.c); printf("%d\n",m.s); m.s = 0; /* reset first 16 bits */ printf("%d\n",m.c); printf("%d\n",m.s); }
union provides multiple ways of using the same memory location.
#include <stdio.h> union mix {/*from ww w . j a v a 2s. c o m*/ char c[4]; /* 4 bytes */ struct { short hi, lo; } s; /* 4 bytes */ int i; /* 4 bytes */ } m; int main(void) { union mix m; m.i=0xFF00F00F; //11111111 00000000 11110000 00001111 m.s.lo; //11111111 00000000 m.s.hi; // 11110000 00001111 m.c[3]; //11111111 m.c[2]; // 00000000 m.c[1]; // 11110000 m.c[0]; // 00001111 printf("%d\n",m.i); printf("%d\n",m.s.lo); }