Mixing signed and unsigned integers in arithmetic operations

suggest change

It is usually not a good idea to mix signed and unsigned integers in arithmetic operations. For example, what will be output of following example?

#include <stdio.h>

int main(void)
{ 
    unsigned int a = 1000;
    signed int b = -1;

    if (a > b) puts("a is more than b");
    else puts("a is less or equal than b"); 

    return 0;
}

Since 1000 is more than -1 you would expect the output to be a is more than b, however that will not be the case.

Arithmetic operations between different integral types are performed within a common type defined by the so called usual arithmetic conversions (see the language specification, 6.3.1.8).

In this case the “common type” is unsigned int, Because, as stated in Usual arithmetic conversions,

714  Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type.

This means that int operand b will get converted to unsigned int before the comparison.

When -1 is converted to an unsigned int the result is the maximal possible unsigned int value, which is greater than 1000, meaning that a > b is false.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents