If I cast an unsigned integer to a signed integer then cast back, am I guaranteed to get the original value? For example, does this function always return true
for any x
on any platform according to the C++ standard?
bool f(unsigned int x)
{
return x == static_cast<unsigned int>(static_cast<int>(x));
}
What about this one?
bool g(int x)
{
return x == static_cast<int>(static_cast<unsigned int>(x));
}
The answer is "no, this is not guaranteed" for both
f
andg
.Here is what the standard says about it:
Section 2 talks about function
g
. The cast ofx
tounsigned
can cause change of representation on systems that do not use two's complement representation, so converting the number back may get you a different value.Section 3 talks about function
f
. When the number is outsidesigned int
's range, the result is implementation-defined, so one is not allowed to make any claims about the result of converting it back to unsigned.