循环的时候坚持使用(signed) 的数据类型的变量作为循环变量

85 篇文章 0 订阅

今天师兄考我一个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, Categoryc 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!

It makes no sense to think that such an error message could depend on pre or post (totally irrelevant here) incrementing or decrementing -- clLoop will take on every possible value either way. Also, if clLoop < 0 is a useless test (as it is), then clLoop >= 0 must also be a useless test, since (clLoop < 0) == !(clLoop >= 0).

possible duplicate of Why does "for (i = 100; i <= 0; --i)" loop forever?

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.

 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值