cif-statementimplicit-conversionunsigned-integersigned-integer

С typecasting in conditions


There is a simple example:

unsigned a = -5;
int b = 5;
if (a + b <= -1){
...
}

To which type will cast a+b? To signed or unsigned? And is it noted in C-standard or compiler will decide what to do?


Solution

  • Due to the usual arithmetic conversions if two objects have the same rank then an object of signed integer type is converted to the unsigned integer type.

    From the C Standard (6.3.1.8 Usual arithmetic conversions)

    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.

    and (6.5.8 Relational operators)

    3 If both of the operands have arithmetic type, the usual arithmetic conversions are performed.

    So in this condition

    if (a + b <= -1){
    

    the both operands a + b and -1 are converted to the type unsigned int.

    That is as a has the type unsigned int then and the expression a + b also has the type unsigned int. As the expression a + b has the type unsigned int then and the expression -1 will also have the type unsigned int (-1 will be converted to the maximum value of the type unsigned int).

    Thus the condition of the if statement will evaluate to the logical true.