怎样做一个反向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:


  1. 这应该是一个倒退的循环。

  2. 循环索引应该是无符号的。

  3. n是无符号常量。

  4. 这不应该是基于无符号整数的晦涩环运算。

任何想法?感谢:)

如何

for (unsigned i = n ; i-- > 0 ; )
{
  // do stuff with i
}