About Union Unused Fields

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 bis int, printf("%d",overflow.b);gives a value of 5. Why is this?

+3
source share
3 answers

In a union, all members have the same memory. When you assign .a, you write the int value to memory. When you refer to .b, you interpret the same bytes that you just wrote int as a float.

(, int float), , - . .

" ", .

b int, , .a int .b int. , , .

+6

printf("%d",overflow.b); - UB ( printf).

printf("%f",overflow.b); - UB (overflow.b ). . ( int, - float). - , , UB

+1

If you set ato something, the part bwill be one, but part bmay be uninitialized data, depending on the sizeof int and float in the system. Interpret it as floating, and who knows what will happen? Nasal demons. Do not do this.

0
source

Source: https://habr.com/ru/post/1796661/


All Articles