怎样做一个反向for循环的无符号索引的最佳方式? [英] What's the best way to do a reverse 'for' loop with an unsigned index?

查看:158
本文介绍了怎样做一个反向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
}

这篇关于怎样做一个反向for循环的无符号索引的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆