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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With