今天师兄考我一个usigned int 的0 自减1 的时候, 会出现的结果(为转型)。
当然如果回答 -1, 那就是打错特错了。 因为是usigned int, 也就不可能出现 -1 的结果。 如果是(signed) int 的形式, 那么okay, 是 -1。
程序员有事范的错误就是在一个循环的时候, 使用unsigned 的int 作为循环变量, 这是不好的一个编程的practice, 如果我们进行和usigned的变量和哦比较的话, 那是pointless。 我常常坚持使用(signed)int 作为循环变量。 PS: google上关于这个问题的解答。
Why Is Comparingif an Unsigned Int >= 0 a “Pointless Comparison”?
Tag: c++, c,for-loop, comparison, unsigned, Category: c Author:wanshangly Date:2011-02-05
I got warning Pe186 "Pointless comparison of unsigned int with zero", when I tried to compile the following code: for(clLoop = cpLoopStart; clLoop >= 0; clLoop--) { //Do something } I don't understand why this is so. I could understand, if I were looking for a value LESS THAN zero, since an unsigned int can never be negative. But all I am looking for here is if it is EQUAL to zero, which an unsigned int certainly can be. I could even see this error if in this loop I tried to pre-decrement instead of post-decrement. Thanks! | ||
|
Other Answer1
You check whether the unsigned int is greater than or equal (>=) zero. This expression will always be true, because unsigned integers will never be less than zero. The compiler tries to warn you that you are about to program an infinite loop. |
Other Answer2
You are checking if an unsigned int is equal or greater than 0. Which is always true. |
Other Answer3(提出了使用usigned的 int 的解决方案)
I think you meant to say for(clLoop = cpLoopStart; clLoop; clLoop--) { //Do something } |
Other Answer4
clLoop >= 0 is always true. It doesn't matter whether you pre-decrement or post-decrement, an unsigned value is at least 0. When you decrement 0 you get UINT_MAX. The compiler figures that you probably don't mean to loop forever (or you'd have used a different construct, that more obviously loops forever), hence the warning. |
Other Answer5
unsigned integer never falls below 0 even after decrementing infinitely (i.e. clLoop >= 0 will always be true) which makes the comparison pointless. |
Other Answer6
The warning complains about your for loop break condition clLoop >= 0. The loop will end if clLoop gets negative, but that will never happen for an unsigned int. |