使用无符号索引执行反向“for"循环的最佳方法是什么? [英] What's the best way to do a reverse 'for' loop with an unsigned index?
本文介绍了使用无符号索引执行反向“for"循环的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我第一次尝试 reverse for 循环 做 n 次的事情是这样的:
My first attempt of reverse for loop that does something n times was something like:
for ( unsigned int i = n-1; i >= 0; i-- ) {
...
}
这个失败是因为在无符号算术中i
保证总是大于或等于零,因此循环条件总是为真.幸运的是,在我不得不怀疑为什么循环无限执行之前,gcc 编译器警告我毫无意义的比较".
This fails because in unsigned arithmetic i
is guaranteed to be always greater or equal than zero, hence the loop condition will always be true. Fortunately, gcc compiler warned me about a 'pointless comparison' before I had to wonder why the loop was executing infinitely.
我正在寻找一种优雅的方式来解决这个问题,请记住:
I'm looking for an elegant way of resolving this issue keeping in mind that:
- 它应该是一个向后的 for 循环.
- 循环索引应该是无符号的.
- n 是无符号常量.
- 它不应基于无符号整数的晦涩"环算术.
有什么想法吗?谢谢:)
Any ideas? Thanks :)
推荐答案
怎么样:
for (unsigned i = n ; i-- > 0 ; )
{
// do stuff with i
}
这篇关于使用无符号索引执行反向“for"循环的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文