Lane Surface
Lane Surface

Reputation: 56

Unexpected Result for Implicit Type Conversion

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.

Upvotes: 1

Views: 101

Answers (1)

Petr Skocik
Petr Skocik

Reputation: 60068

-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.

Upvotes: 1

Related Questions