Rick de Water
Rick de Water

Reputation: 2642

Cast unsigned to signed and back

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.

Upvotes: 7

Views: 3281

Answers (2)

alexeykuzmin0
alexeykuzmin0

Reputation: 6440

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.

Upvotes: 6

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385395

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

Upvotes: 0

Related Questions