Search code examples
cimplicit-conversionarithmetic-expressions

What would be the output of the following code snippet and why?


#include <stdio.h>
#include <stdlib.h>
typedef    unsigned     int    U32;
int main() {
    U32 var     = -1;
    printf("var = %u\n", var);
    if(var != -1)
    {
        printf("\n I'm not -1\n");
    }
    else
    {
        printf("I'm -1 and Var :%u\n", var);
    }
 }

Here "-1" should be converted into an unsigned int and it should be assigned to var. And then at the if condition it should not be equal to -1. But it is going into the else statement.


Solution

  • Please note that all integer constants such as 1 have a type. Given that U32 is unsigned int, then:

    • In the case of U32 var = -1; (assignment), the right operand of type int is converted to the type of the left operand.

    • In the case of if(var != -1), the -1 operand is converted from type int to unsigned int as per the usual arithmetic conversions, details here: Implicit type promotion rules

    In both cases, a signed to unsigned conversion occurs and such a conversion is well-defined as per 6.3.1.3:

    Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.

    Meaning that in both cases above, the same unsigned value 0xFFFFFFFF will be generated.