Search code examples
cunsignedsigned

conversion of unsigned integer variable to signed variable


why does below program gives the output that b is greater than a? Even though b contains -2.

void main()
{
    unsigned int a=12;
    int b=-2;

    if(a>b)
        printf("a is greater");
    else
        printf("b is greater");

    getch();
}

Solution

  • To perform the comparison, both operands are first converted to the same type. In this case, int b is converted to the higher ranking unsigned. For the comparison values, it is then 12 > (-2 + (UINTMAX + 1))? which is false.

    To compare in the usual mathematical sense:

    unsigned int a;
    int b;
    
    if ((b < 0) || (a > b)) printf("a is greater");