if we set float and double type to NaN then they are not equal to anything including themselves.
can such a thing happens for
This perfectly possible if you compare uninitialized variables.
In C++ language an uninitialized variable is not guaranteed to hold a stable value. In theory operating with uninitialized values produces undefined behavior. In practice reading the value of the same uninitialized variable multiple times can easily result in different values being read. The most obvious practical reason for this is that the variable was optimized to some CPU register.
In order to manage the limited amount of CPU registers efficiently, optimizing compilers operate with the notion of value lifetime of a variable. Value lifetime is essentially the period during which the variable holds a specific stable value. Value lifetime begins when the variable is initialized and ends when it is re-initialized to another value (or when its accessed for the very last time). Within the period of "value lifetime", the value must be stable, so the CPU register cannot be used for other purposes (or it have to be carefully saved and restored every time it is used for other purposes).
Outside the period of value lifetime, there's no need to preserve the value of the register, so it can be freely used for other purposes. For this reason, if some variable is represented by a CPU register, but not initialized (i.e. if its value lifetime hasn't begin yet) its observed value can change absolutely unpredictably, producing the new value every time the variable is read, because the contents of the corresponding CPU register changes for some unrelated reasons.
This might easily result in a == a
evaluating to false
with uninitialized a
. Of course, it is rather surprising to see it happen for two reads that appear to be located so "close" together. But it still can happen. This behavior is prefectly standard. The standard does not guarantee the stability of an initialized variable.