Comparison operation on unsigned and signed integers

后端 未结 7 2126
小蘑菇
小蘑菇 2020-11-22 04:17

See this code snippet

int main()
{ 
 unsigned int a = 1000;
 int b = -1;
 if (a>b) printf(\"A is BIG! %d\\n\", a-b);
 else printf(\"a is SMALL! %d\\n\", a         


        
7条回答
  •  無奈伤痛
    2020-11-22 04:38

    You are doing unsigned comparison, i.e. comparing 1000 to 2^32 - 1.

    The output is signed because of %d in printf.

    N.B. sometimes the behavior when you mix signed and unsigned operands is compiler-specific. I think it's best to avoid them and do casts when in doubt.

提交回复
热议问题