a"); } else { printf("< a"); } } I am tr...">

Holistic C Promotion Example

void foo(void) { unsigned int a = 6; int b = -20; if (a+b > a) { printf("> a"); } else { printf("< a"); } } 

I am trying to understand what is happening with the whole promotion example given above. I know that for a = 6 and b = -20 output should be > a , since b advances to unsigned int . However, the output will be < a if I assign b = -5 . Shouldn't the output be the same in this case, since the value b = -5 also increases to unsigned int ?

+5
source share
1 answer

The reason for this is due to the method in which the signed value is converted to unsigned. Section 6.3.1.3 of Standard C , regarding conversions of signed and unsigned integers, defines how this happens:

2 Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting 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)

...

60) The rules describe arithmetic by mathematical value, and not by the value of this type of expression.

In your example with b equal to -20, when it is converted to unsigned UINT_MAX + 1 , it is added to the value, so the converted value of UINT_MAX - 19 . When you add the value of a (6), you will get UINT_MAX - 13 . This value is greater than a , so "> a" is printed.

If you set b to -5, the converted value of UINT_MAX - 4 . Adding 6 to this gives you UINT_MAX + 2 . Since the math value on unsigned int occurs modulo UINT_MAX + 1 , the actual result is 1. This is less than 6, so "< a" is printed.

In addition, there is not integer advancement, but an integer conversion . Promotion occurs first if any integer type in the expression has a rank less than int . This is not true.

+9
source

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


All Articles