If you were instead just looking to get the absolute value, you should have used the
abs() function from
Otherwise, when you make such a cast, you trigger the following conversion rule from C17 188.8.131.52:
Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type. 60)
Where foot note 60) is important:
- The rules describe arithmetic on the mathematical value, not the value of a given type of expression.
Mathematical value meaning we shouldn’t consider wrap-around etc when doing the calculation. And the signedness format (2’s complement etc) doesn’t matter either. Applying this rule, then:
- You have mathematical value
-4and convert from
- We add one more than the maximum value. That is
-4 + USHRT_MAX + 1, where
UINT_MAXis likely 2^16 = 65535.
-4 + 65535 + 1 = 65532. This is in range of the new type
- We got in range at the first try, but “repeatedly adding or subtracting” is essentially the same as taking the value modulo (max + 1).
This conversion is well-defined and portable – you will get the same result on all systems where
short is 16 bits.
Read more here: Source link