if we set float and double type to NaN then they are not equal to anything including themselves.
can such a thing happens for
No. The comparation for floats is defines in such way, that NaN compared to any number will return false. Anyway, for ints there is another formula:
ZF = !(a ^ b);
That will give true for any possible value of a.
EDIT: on GCC, with any -O flag, the comparation just dissapears to true.
Although it's certainly unusual, C++ does allow int
to be NaN
.
First, it's possible for int
to store information besides its numeric value. §3.9.1/1:
For character types, all bits of the object representation participate in the value representation. For unsigned character types, all possible bit patterns of the value representation represent numbers. These requirements do not hold for other types.
Then, numeric_limits<int>::has_quiet_NaN
and has_signaling_NaN
are not required to be false
for any type. §18.2.1.2/34-36:
static const bool has_quiet_NaN;
34 True if the type has a representation for a quiet (non-signaling) ‘‘Not a Number.’’
35 Meaningful for all floating point types.
36 Shall be true for all specializations in which is_iec559 != false.
"Meaningful for all floating point types" is a little troublesome as it opens the possibility that the value could be meaningless, but that's certainly an extrapolation.
If numeric_limits<int>::has_quiet_NaN == true
, then numeric_limits<int>::quiet_NaN()
returns such a value.
Obviously, this is not something you should worry about in your code.
Anything can happen if you compare an uninitialized variable to itself. It is after all undefined behavior. For initialized int variables, this can't happen.
Note that namespace-scope, class-static, and function-static int variables not explicitly initialized are given the value 0. Then they won't compare equal.
I have just tested with Clang:
int main() {
int x;
return (x == x);
}
When compiled with -O1, this returns 0 because the optimizer is allowed to assume that x has no stable value.
GCC is more forgiving with the above, returning 1. The following makes GCC return 0 too (obviously not doing the branch is cheaper if you are allowed to choose):
int main() {
int x;
if(x == x) {
return 1;
}
return 0;
}
In the end, the result is not only dependent on the CPU executing the code, but also from anything else in the toolchain.