The answer is "no, this is not guaranteed" for both f
and g
.
Here is what the standard says about it:
4.7 Integral conversions
- If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source
integer (modulo 2n where n is the number of bits used to represent the unsigned type). [ Note: In a two’s
complement representation, this conversion is conceptual and there is no change in the bit pattern (if there is no truncation). — end note ]
- If the destination type is signed, the value is unchanged if it can be represented in the destination type; otherwise, the value is implementation-defined.
Section 2 talks about function g
. The cast of x
to unsigned
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 outside signed 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.
f
will obviously underflow so you will obviously not get the same value back. – Darrickdarrillf(-1)
gives me4294967295
. I don't find that very surprising. Either way, it's "undefined behavior". – Darrickdarrillgcc 5.3.1
, yourf(-1)
, in the code you showed, returned1
. One of us is very, very confused. – Rydderf(-1)
is still doing a==
comparison, as shown in this question. – Rydder