I have a strange behavior I'd like to understand. I have the following code:
union floatInt
{
float f;
unsigned int l;
};
floatInt A, B;
A.l = 0xFFA70B56;
B.f = A.f;
std::cout << std::hex << B.l << std::endl;
This works fine except in 1 configuration: Linux in non-debug mode, then I have this result: ffe70b56
And I don't really understand why the value has changed. I've been through several points to understand this:
cppreference/union specifies that
It's undefined behavior to read from the member of the union that wasn't most recently written. Many compilers implement, as a non-standard language extension, the ability to read inactive members of a union.
But what would be the purpose of a union if we cannot use the other members? Moreover, it points to the same memory location, so it shouldn't be different.
- The value I'm using (0xFFA70B56) is NAN in IEEE 754 standard. So, when it is affected to another variable, can it be interpreted and changed to another NAN value like 0xFFE70B56?
- If I declare B as volatile, then the error disappears. Note that the variable isn't used anywhere else in the code. So has it something to do with compiler optimization?