Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

conversion of unsigned integer variable to signed variable

Tags:

c

unsigned

signed

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();
}
like image 902
Lincoln Avatar asked Dec 11 '25 13:12

Lincoln


1 Answers

First, to quote the C11 standard for relational operators, chapter 6.5.8

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

Now, following the description in chapter 6.3.1.8, Usual arithmetic conversions, if you try to perform arithmetic operation between a signed and an unsigned integer (type), the signed one will get promoted to unsigned type (higher rank) and then the operation will take place.

So, here, for the comparison, the value of b is getting converted to unsigned type and you're getting the wrong output there.

To quote the relevant part, from the same chapter

[...] Otherwise, both operands are converted to the unsigned integer type corresponding to the type of the operand with signed integer type.

You can also check on the usual arithmetic promotion rule here

That said, void main() should be int main(int argc, char* argv[]), or, at least, int main(void).

like image 90
Sourav Ghosh Avatar answered Dec 14 '25 09:12

Sourav Ghosh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!