怎样做一个反向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:
- 这应该是一个倒退的循环。
- 循环索引应该是无符号的。
- n是无符号常量。
- 这不应该是基于无符号整数的晦涩环运算。
任何想法?感谢:)
答
如何
for (unsigned i = n ; i-- > 0 ; )
{
// do stuff with i
}