Print Type Variable - Odd Behavior

#include <stdio.h>

union p{
    int x;
    float y;
};

int main()
{
    union p p;
    p.x = 10; 
    printf("%f\n", p.y);
    return 0;
}

Conclusion:

0.000000

When I try to compile the above program, it does not show any warnings, even in the main function. Why printfdoesn't it print the value 10.00000?

I read some related questions about stackoverflow, which explains the behavior printfwhen printing an integer without typecasting using the float specifier, but I think this is a different case here. I am printing a floating point number using the float specifier. It should print the correct value. Can anyone explain what is going on here?

+4
source share
3 answers

, int float . 32- int float, -endian IEEE-754, :

0000 1010 0000 0000 0000 0000 0000 0000

( ) , 0.000000 %f ( , printf). %e f.s., :

1.401298e-44

C99 %a f.s., , , 2 (.. ):

0x1.4p-146
+5

10 x. p.x = 1092616192 p.x = 10, , https://en.wikipedia.org/wiki/IEEE_floating_point

10 10.f .

+4

int float, , %e, p.f:

1.401298e-44

IEEE 754 single precision float 4 bytes int, float convertor, , , 40 IEEE 754.

40 :

0x42200000

p.x:

p.x = 0x42200000;

, 40 p.y, .

This is always a discussion about whether the punning type through unified unified behavior is not, as I understand it, and in practice, compilers explicitly support this punning type, here is the gcc link explaining its support .

+3
source

All Articles