Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printing union variable - odd behaviour

#include <stdio.h>

union p{
    int x;
    float y;
};

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

Output:

0.000000

When I am trying to compile above programs, it is not showing any warnings, even in the main function. Why is printf not printing value 10.00000?

I have read some related questions on stackoverflow which explains behavior of printf while printing integer without typecasting with float specifier, but i think here it is a different case. I am printing float number with float specifier. It should print the proper value. Can anyone explain what is happening here?

like image 595
Jagdish Avatar asked Oct 03 '14 14:10

Jagdish


1 Answers

This is due to a fact that both int and float objects have different binary representations. Assuming 32-bit int and float, little-endian and IEEE-754 representation, you have binary pattern as:

0000 1010 0000 0000 0000 0000 0000 0000

that is (in context of floating number) very small number, which has printed value as 0.000000 using %f format specifier (one may say that is rounded by printf). You might try with %e f.s., which results into another output:

1.401298e-44

C99 introduced %a f.s., which represents floating-number exactly as it's stored, namely as 2-base floating-point number (i.e. with mantissa and exponent):

0x1.4p-146
like image 95
Grzegorz Szpetkowski Avatar answered Nov 08 '22 14:11

Grzegorz Szpetkowski