Take this code snippet as 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 a printf("%f",overflow.b); i get zero on gcc and garbage on turbo.
Can you explain me why this happens.
What exactly happens to the unused variables in a union?
Also if b is an int, printf("%d",overflow.b); gives value 5. Why is this?
In a union, all members share the same memory. When you assign to
.a, you are writing an int value into the memory. When you access.b, you are interpreting those same bytes you just wrote an int into, as a float.When the members are different sizes (as int and float might be), then some bytes will be changed while others are not. You may be accessing uninitialized memory when looking at the larger member.
There are no “unused variables”, in a union, just unused interpretations of the common memory.
When you make
ban int, you are saying that.ashould interpret the bytes as an int, and that.bshould also interpret the bytes as an int. In other words, it’s useless to declare two members of the same union as the same type.