1

I am trying to cause an implicit type conversion between an int and unsigned int in some code that I wrote. The compiler gives an unexpected result.

According to the rules for implicit conversion between signed and unsigned integers (of equal rank), the code should produce a large positive number as its output.

unsigned int q = 90;
int w = -1;
printf("q+w=%u\n", q + w);

As the output to this program, which you can view here, the result is 89. I would expect the int w to be coerced to the type unsigned int before arithmetic occurs, however, and produce the expected result.

Lane Surface
  • 56
  • 1
  • 6
  • @user3121023 You're totally right. Assigning abs(w)-1 to `q` gives `UINT_MAX` now, as demonstrated [here](https://onlinegdb.com/rJCCJvhAE). – Lane Surface Jun 10 '19 at 22:57
  • 1
    @user3121023: Correct -- except that you can drop the "maybe". – Keith Thompson Jun 10 '19 at 23:11
  • Your compiler, with the appropriate warnings enabled ( for `gcc`, the appropriate option is `-Wconversion` ) warns you that this implicit conversion can result in an incorrect result – user3629249 Jun 12 '19 at 03:33

1 Answers1

1

-1 gets converted to UINT_MAX (the formal rule for converting to unsigneds is that you repeatedly add or subtract the maximum+1 until the result fits (6.3.1.3p2)). UINT_MAX+90 == 89.

Petr Skocik
  • 58,047
  • 6
  • 95
  • 142