2

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));
}
15
  • @sleeptightpupper I've made a mistake in my code. Sorry for the misleading. Commented May 26, 2016 at 2:03
  • I wasn't asking about that. I'm asking for what interval of values you're worried about. i.e, a negative value for f will obviously underflow so you will obviously not get the same value back. Commented May 26, 2016 at 2:04
  • @sleeptightpupper - you should try this with negative values yourself. You'll be shocked and surprised at the results. Commented May 26, 2016 at 2:05
  • 3
    @sleeptightpupper It's not undefined behavior, it is implementation-defined behavior. Commented May 26, 2016 at 2:13
  • 2
    "If the destination type is signed, the value is unchanged if it can be represented in the destination type (and bit-field width); otherwise, the value is implementation-defined." Commented May 26, 2016 at 2:28

1 Answer 1

7

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

  1. 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 ]
  2. 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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.