Take this code snippet as an example:
union stack {
int a;
float b;
};
union stack overflow;
overflow.a = 5;
When I do a printf("%d",overflow.b);
, I get zero on both gcc and turbo. When I do printf("%f",overflow.b);
, I get zero on gcc and garbage on turbo.
Can you explain to me why this is happening. What exactly happens to unused variables in a union?
Also, if b
is int
, printf("%d",overflow.b);
gives a value of 5. Why is this?
source
share