Search code examples
ctypesintegertype-conversioninteger-promotion

Is the promotion to unsigned done on the result or on each operand?


In the following:
2147483647U > -2147483647 - 1 it will evaluate to false because of the conversion/promotion to unsigned.
My question is though how it will be promoted?
Will the subtraction operation be done first and the result will be promoted to unsigned or each operand will be promoted to unsigned instead?
Example with 4 bits [-8,7] for signed and [0,15] for unsigned:
7U > -7 -1
Will this become (unsigned)(-7) + (unsigned)(-1) = (9U) + (15U) = 24U
So we end up 7U > 24U which is false.
Or will we have
-7-1 = -8 = 8U
So 7U > 8U which is false


Solution

  • This expression

    2147483647U > -2147483647 - 1
    

    has two operators where minus has a higher priority than logical >.

    So at first there is calculated sub-expression

    -2147483647 - 1
    

    The both operands have type int. it is their common type. So neither promotion will be done. You will get

    -2147483648
    

    Then expression

    2147483647U > -2147483648
    

    is evaluated.

    Here the common type is unsigned int. Signed and unsigned int have the same rank nevertheless in such cases the common type is unsigned int.

    In this expression simply the internal representation of the right operand is interpretated as unsjgned value. So if it is greater than the left operand then the result will be equal to false.

    If to consider this example

    7U > -7 -1
    

    then -7 - 1 will be equal -8. Internal representation of -8 is

    1000
    

    As unsigned int it is equal to 8. Thus

    7u > 8u
    

    is equal to false.