虽然语句不能进入 [英] Cannot enter in while statement
问题描述
可能重复:结果
无符号和符号比较结果
unsigned int类型和符号字符比较
我有一个奇怪的现象,当我尝试在这个while语句进入:
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++;
}
但它从来没有进入,即使当我设置一个断点 I = -2
和 U = 0
。
我究竟做错了什么?我怎么能解决这个问题?
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?
推荐答案
这是因为ANSI C标准定义,只要有一个合格的(你的之间的比较无符号整数U
)和非限定的类型(你的 INT I
),非限定类型提升为一种同类型的(因此总是 INT
),但也继承了其他数量的预选赛(即变成无符号
)。
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
).
当你的 INT
,其值等于 -2
,becames 无符号
的第一个字节经历这种转变: 0000 0010 - &GT; 1111 1110
。你的 INT
现在是一个非常大的正数,你的 unsigned int型的肯定更大
。
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.
这篇关于虽然语句不能进入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!