union UnionName
{
datatype1 varName1; // List of variables
datatype2 varName2;
...
};
|
Meaning:
|
Defining a union typed variable:
|
|
union myUnion // Union structure
{
int a;
double b;
short c;
char d;
};
struct myStruct // Struct with the same member variables
{
int a;
double b;
short c;
char d;
};
int main(int argc, char *argv[])
{
struct myStruct s; // Define a struct
union myUnion u; // and a union variable
// Print the size and the address of each component
printf("Structure variable:\n");
printf("sizeof(s) = %d\n", sizeof(s) );
printf("Address of s.a = %u\n", &(s.a) );
printf("Address of s.b = %u\n", &(s.b) );
printf("Address of s.c = %u\n", &(s.c) );
printf("Address of s.d = %u\n", &(s.d) );
putchar('\n');
printf("Union variable:\n");
printf("sizeof(u) = %d\n", sizeof(u) );
printf("Address of u.a = %u\n", &(u.a) );
printf("Address of u.b = %u\n", &(u.b) );
printf("Address of u.c = %u\n", &(u.c) );
printf("Address of u.d = %u\n", &(u.d) );
}
|
Output:
Structure variable: sizeof(s) = 24 Address of s.a = 4290768696 Address of s.b = 4290768704 Address of s.c = 4290768712 Address of s.d = 4290768714 Union variable: sizeof(u) = 8 Address of u.a = 4290768688 (Same location !!!) Address of u.b = 4290768688 Address of u.c = 4290768688 Address of u.d = 4290768688 |
How to run the program:
|
|
|
|