6

I have an unsigned value that needs to pass through a function as a signed value (it is not touched by the function). When it comes out I cast it back to unsigned. I know that the result of a cast to signed is implementation defined when overflowing, but can I at least guarantee that I end up with the same value when I cast it back (like with function pointers)?

Example:

int32_t function_with_default(int32_t a_Default)
{
    // Try some stuff
    // ...

    // Fall back to default
    return a_Default;
}

void main()
{
    uint32_t input = UINT32_MAX;
    uint32_t output = static_cast<uint32_t>(function_with_default(static_cast<int32_t>(input));

    // Is is guarenteed to be true?
    input == output;
}

I do have the guarentee that the signed integer is always bigger or equal than the unsigned integer in bytes, so no data should be lost due to lack of space.

Rick de Water
  • 2,388
  • 3
  • 19
  • 37

2 Answers2

6

No, you don't have such guarantee: [conv.integral]

2 If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2^n 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 ]

3 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.

alexeykuzmin0
  • 6,344
  • 2
  • 28
  • 51
  • 3
    Or - conversely, yes you DO have this guarantee, as long as your value doesn't exceed the range of what you're casting to. – UKMonkey Dec 09 '16 at 10:35
0

No, you can't, because the result of a cast to signed is implementation defined when overflowing.

Community
  • 1
  • 1
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055