Cannot enter in while statement [duplicate]

江枫思渺然 提交于 2020-01-24 00:18:13

问题


Possible Duplicate:
Unsigned and signed comparison
unsigned int and signed char comparison

I have a strange behavior when i try to enter in this while statement:

unsigned u = 0;
int i = -2;

while(i < u)
{
    // Do something
    i++;
}

But it never enters, even if when i set a break point i = -2 and u = 0. What am I doing wrong? How could i fix this?


回答1:


It's because the ANSI C standard defines that whenever there is a comparison between a qualified (your unsigned int u) and a non qualified type (your int i), the non qualified type gets promoted to a type of the same type (thus always int), but also inherits the qualifiers of the other quantity (i.e. it becomes unsigned).

When your int, whose value is equal to -2, becames unsigned the first byte undergoes this transformation: 0000 0010 -> 1111 1110. Your int is now a very large positive number, certainly larger of your unsigned int.

There is a solution: cast to signed

while(i < (signed) u)
{
    // Do something
    i++;
}

By the way, probably your compiler should give you a warning.




回答2:


You are comparing a signed and unsigned integer and your problems started there...
Don't do that and it should work just fine.



来源:https://stackoverflow.com/questions/10849724/cannot-enter-in-while-statement

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!