Search code examples
c++cfloating-pointunions

union consisting of float : completely insane output


#include <stdio.h>

union NumericType
{
    float value;
    int intvalue;
}Values;

int main()
{
    Values.value = 1094795585.00;
    printf("%f \n",Values.value);
    return 0;
}

This program outputs as :

1094795648.000000 

Can anybody explain Why is this happening? Why did the value of the float Values.value increase? Or am I missing something here?


Solution

  • First off, this has nothing whatsoever to do with the use of a union.

    Now, suppose you write:

    int x = 1.5;
    printf("%d\n", x);
    

    what will happen? 1.5 is not an integer value, so it gets converted to an integer (by truncation) and x so actually gets the value 1, which is exactly what is printed.

    The exact same thing is happening in your example.

    float x = 1094795585.0;
    printf("%f\n", x);
    

    1094795585.0 is not representable as a single precision floating-point number, so it gets converted to a representable value. This happens via rounding. The two closest values are:

    1094795520 (0x41414100) -- closest `float` smaller than your number
    1094795585 (0x41414141) -- your number
    1094795648 (0x41414180) -- closest `float` larger than your number
    

    Because your number is slightly closer to the larger value (this is somewhat easier to see if you look at the hexadecimal representation), it rounds to that value, so that is the value stored in x, and that is the value that is printed.