c - conversion of unsigned integer variable to signed variable -


why below program gives output b greater a? though b contains -2.

void main() {     unsigned int a=12;     int b=-2;      if(a>b)         printf("a greater");     else         printf("b greater");      getch(); } 

first, quote c11 standard relational operators, chapter 6.5.8

if both of operands have arithmetic type, usual arithmetic conversions performed.

now, following description in chapter 6.3.1.8, usual arithmetic conversions, if try perform arithmetic operation between signed , unsigned integer (type), signed 1 promoted unsigned type (higher rank) , operation take place.

so, here, comparison, value of b getting converted unsigned type , you're getting wrong output there.

to quote relevant part, same chapter

[...] otherwise, both operands converted unsigned integer type corresponding type of operand signed integer type.

you can check on usual arithmetic promotion rule here

that said, void main() should int main(int argc, char* argv[]), or, @ least, int main(void).


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -