c – Convert negative integer to positive integrer using casting

If you were instead just looking to get the absolute value, you should have used the abs() function from <stdlib.h>.

Otherwise, when you make such a cast, you trigger the following conversion rule from C17 6.3.1.3:

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:

  1. 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 -4 and convert from signed short to unsigned short.
  • We add one more than the maximum value. That is -4 + USHRT_MAX + 1, where UINT_MAX is likely 2^16 = 65535.
  • -4 + 65535 + 1 = 65532. This is in range of the new type unsigned short.
  • 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