In a structure, the data type of each field is unique; Using unions, you can store different data types in one field.
Different data types share a piece of memory. Of course, its memory size should be based on the big.
The data in the joint, either or, only one is valid; There should be a description of what type is useful at this time in a data.
In addition to shared memory, federation is the same as structure.
1. The size of the union is the size of the largest data member:
#include <stdio.h>
int main(void)
{
union MyUnion {
short n1;
int n2;
double n3;
};
printf("%u, %u\n", sizeof(union MyUnion), sizeof(double));
getchar();
return 0;
}
2. Union is characterized by shared memory, which modifies one other variable:
#include <stdio.h>
#include <limits.h>
int main(void)
{
union MyUnion {
unsigned char n1;
unsigned short n2;
unsigned int n3;
} U = {0};
printf("%10u, %10u, %10u\n", U.n1, U.n2, U.n3);
U.n2 = USHRT_MAX;
printf("%10u, %10u, %10u\n", U.n1, U.n2, U.n3);
U.n3 = INT_MAX;
printf("%10u, %10u, %10u\n", U.n1, U.n2, U.n3);
U.n1 = 0;
printf("%10u, %10u, %10u\n", U.n1, U.n2, U.n3);
getchar();
return 0;
}