Send unsigned and signed

I have an unsigned value that should go through the function as a signed value (this will not affect the function). When he comes out, I return him without a sign. I know that the result of the casting to signing is an implementation defined during overflow, but can I at least guarantee that I get the same value when I return it (for example, 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 have guarentee that a signed integer is always greater than or equal to an unsigned integer in bytes, so no data should be lost due to lack of space.

+6
source share
2 answers

No, you do not have such a guarantee: [conv.integral]

2 If no destination type is specified, the resulting value is the smallest unsigned integer comparable to the integer source (modulo 2 ^ n, where n is the number of bits used to represent the unsigned type). [Note: twice the addition, this conversion is conceptual and there are no changes in the bit scheme (if there is no truncation). -end note]

3 If the destination type is signed, the value does not change if it can be represented in the destination type; otherwise, the value is determined by the implementation .

+6
source

No, you cannot, because the result of casting to a signature is an implementation defined during an overflow.

0
source

Source: https://habr.com/ru/post/1013030/


All Articles