2
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int i;
    unsigned int k;
    k = 2; 
    i = -1;
    if (k+i > 1 ) /* if i write ( (k+i) > 1) i get the same result */
    {
        printf("i converted to unsigned \n");
    }
    else
    {
        printf("i remains negative\n i: %d \n ", i );
    }
    
    return 0;
}

according to the integer promotion, the output should be a very high number. I'm confused, is it something that im missing? the output here is 1, but in the line where: if((k+i) > 1) "i" should be converted to unsigned. I have searched a lot but it seems that others get different results, im sure im using c.(visual code)

Mujin
  • 23
  • 4
  • See also https://stackoverflow.com/questions/2280663/in-a-c-expression-where-unsigned-int-and-signed-int-are-present-which-type-will – Ben Zotto Aug 21 '20 at 17:22
  • It looks like promotion is done after the addition is done. – Tarik Aug 21 '20 at 17:24
  • Initialize `j` in your code. – ryyker Aug 21 '20 at 17:24
  • Think, what will happen if `-1` is converted to unsigned? Ir will become `0xFFF..FF` (assuming 2's complement). So your addition will wrap around and will become `1`. Equivalent to subtracting `1`. So your `if` condition is not testing the right thing. – Eugene Sh. Aug 21 '20 at 17:27
  • Specifically which unsigned int value do you expect `k+i` to be? – Paul Hankin Aug 21 '20 at 17:32
  • Mujin - It is perfectly fine if you would like to interact or respond to any of these comments :) – ryyker Aug 21 '20 at 17:42
  • The conversions that occur in evaluating `k+i > 1` affect only values used in the expression. The types and stored values of `k` and `i` do not change. When we say, in evaluating `k+i`, that `i` is converted to `unsigned`, that is just a figure of speech. `i` itself is not converted. Its value is taken, and then, from that `int` value, an `unsigned` value is calculated, and that value is used in the expression. – Eric Postpischil Aug 21 '20 at 18:08

2 Answers2

1

Overflow:

  -1 = 0xFFFFFFFF       base 2: 1111 1111  1111 1111  1111 1111  1111 1111 
   2 = 0x00000002       base 2: 0000 0000  0000 0000  0000 0000  0000 0010  
+ ---------------     + --------------------------------------------------
       0x00000001               0000 0000  0000 0000  0000 0000  0000 0001

with an overflow of 1 on the left side of the result.

1

"...the output should be a very high number..."

Using the "%x" format specifier, you can see that your assumption is correct, If unsigned, it would be large:

printf("i remains negative\n i: 0x%X \nj: %ld ", i , j);// j is inited to 0 here

results in

i: 0xFFFFFFFF  

(4294967295 in decimal. But using "%d", the result is -1)

ryyker
  • 22,849
  • 3
  • 43
  • 87