if we set float and double type to NaN then they are not equal to anything including themselves.
can such a thing happens for
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.