When x==x Evaluates to FALSE in C/C++?


It might seem obvious at first that the following expression in C/C++ (or any other) programming language evaluates to true, in most of the cases (well, Javascript may also have some weird stuffs).

1
2
3
4
5
if (x == x) {
   cout << "equal";
} else {
   cout << "different";
}
if (x == x) {
   cout << "equal";
} else {
   cout << "different";
}

It has one exception in C/C++, if the IEEE754 32-bit single float type is involved. If we define:

1
float x = 0xffffffff;
float x = 0xffffffff;

We are basically trying to assign a 32-bit integer (signed or unsigned, doesn’t matter) 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 x is not the same as the integer 0xffffffff. So float x is roughly equal to:

1
float x = 4294967296.000000;
float x = 4294967296.000000;

However, if we copy the memory directly, let’s say, we have a integer (value equal to 0xffffffff), and we copy over the content (memory values):

1
2
int a = 0xffffffff;
memcpy(&x, &a, sizeof(x));
int a = 0xffffffff;
memcpy(&x, &a, sizeof(x));

Well, the 0xffffffff in IEEE754 is not a valid float number (it is used to represent the constant NAN = Not a Number), so if you compare this invalid representation to itself, it is not equal.

1
2
3
4
5
if (x == x) {
   cout << "equal";
} else {
   cout << "different";  // output different 
}
if (x == x) {
   cout << "equal";
} else {
   cout << "different";  // output different 
}

And NAN is neither larger or equal to zero, nor smaller than zero. The following will output a ‘Bingo’;

1
2
3
4
5
6
7
if (x >= 0) {
  cout << "larger or equal zero";
} else if (x < 0) {
  cout << "smaller than zero";
} else {
  cout << "Bingo";
}
if (x >= 0) {
  cout << "larger or equal zero";
} else if (x < 0) {
  cout << "smaller than zero";
} else {
  cout << "Bingo";
}

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
356 words
Last Post: How to Clear CloudFlare Caches of Multiple URLs using PHP Script with CloudFlare API?
Next Post: Cloudflare Offers Dedicated SSL Certificates

The Permanent URL is: When x==x Evaluates to FALSE in C/C++?

9 Comments

  1. Kamil Koczurek
  2. John Morrison
      • John Morrison
          • John Morrison
            • Paweł
    • mathchuong89
    • Kamil Koczurek

Leave a Reply