jbsu32 jbsu32 - 2 months ago 7
C Question

What is the logic behind this behavior in union?

I have declared an union with 2 structures and assigned values to each of the elements and then printed them.

union data {
struct s1 {
int a;
int b;
}c;
struct s2 {
int d;
int e;
}f;
} x;

/* Assignment */
x.c.a=1;
x.f.e=2;
x.c.b=3;
x.f.d=4;

printf("%d %d %d %d\n", x.c.a, x.f.e, x.c.b, x.f.d);


It outputs like this ->
4 3 3 4


But, when I assign the values in the follwing order ->

x.c.b=3;
x.f.d=4;
x.c.a=1;
x.f.e=2;


It outputs like this ->
1 2 2 1


What is the logic behind this variation ??

Answer

A union has enough space to store the largest of its members. In your case, both members are of the same size. The memory layout for x is such that it can hold two ints.

x.c.a=1;    // Sets the value of the first int to 1
x.f.e=2;    // Sets the value of the second int to 2
x.c.b=3;    // Sets the value of the second int to 3
x.f.d=4;    // Sets the value of the first int to 4

At the end of those statements, you have 3 in the first int and 4 in the second int.

printf("%d %d %d %d\n", x.c.a, x.f.e, x.c.b, x.f.d);

is equivalent to:

int i1 = x.c.a;  // i1 is 4
int i2 = x.c.b;  // i2 is 2

printf("%d %d %d %d\n", i1, i2, i2, i1);

Which produces the output 4 3 3 4.


When you use:

x.c.b=3;    // Sets the value of the second int to 3 
x.f.d=4;    // Sets the value of the first int to 4
x.c.a=1;    // Sets the value of the first int to 1
x.f.e=2;    // Sets the value of the second int to 2

At the end of those statements, you have 1 in the first int and 2 in the second int.

That explains the second output.

Comments