Assigning an integer to float and comparison in C/C++

Consider the below C++ program and predict the output.

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <iostream>
using namespace std;
  
int main()
{
    float f = 0xffffffff;
    unsigned int x = 0xffffffff; // Value 4294967295
    if (f == x) 
        cout << "true";
    else 
        cout << "false";
    return 0;
}

chevron_right


The output of above program is false if the “IEEE754 32-bit single float type” is used by compiler. If we define:

filter_none

edit
close

play_arrow

link
brightness_4
code

float f = 0xffffffff;

chevron_right


We are basically trying to assign a 32-bit integer (signed or unsigned) to a 32-bit float. The compiler will first convert the integer 0xffffffff to a nearest 32-bit float, and the memory representation of the float f is not the same as the integer 0xffffffff. We can see the above values by printing f and x.

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <iostream>
using namespace std;
  
int main()
{
    float f = 0xffffffff;
    unsigned int x = 0xffffffff; 
    cout << "f = " << f << endl;
    cout << "x = " << x << endl;
    return 0;
}

chevron_right


Output :

f = 4.29497e+09
x = 4294967295

Even if we copy the memory directly, for example, we have an integer (value equal to 0xffffffff), and we copy over the content (memory values). Since the 0xffffffff in IEEE754 is not a valid float number, so if you compare this invalid representation to itself, it is not equal.

filter_none

edit
close

play_arrow

link
brightness_4
code

unsigned int x = 0xffffffff;
memoryCopy(&f, &x, sizeof(x));

chevron_right


This article is contributed by Rishav Raj. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.