反向迭代的无符号循环变量 [英] Reverse iteration with an unsigned loop variable

查看:129
本文介绍了反向迭代的无符号循环变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经讨论与同事利用为size_t的。已经想出一个问题是,递减循环变量,直到它达到零的循环

I've been discussing the use of size_t with colleagues. One issue that has come up is loops that decrement the loop variable until it reaches zero.

考虑以下code:

for (size_t i = n-1; i >= 0; --i) { ... }

这会导致一个无限循环,由于无符号整数环绕。你怎么在这种情况下怎么办?这似乎远易写上面的code和不知道你犯了一个错误。

This causes an infinite loop due to unsigned integer wrap-around. What do you do in this case? It seems far to easy to write the above code and not realise that you've made a mistake.

这是我们队的两个建议是使用下列方式之一:

Two suggestions from our team are to use one of the following styles:

for (size_t i = n-1; i != -1 ; --i) { ... }

for (size_t i = n; i-- > 0 ; ) { ... }

但我不知道其他的选择还有...

But I do wonder what other options there are...

推荐答案

我个人是来这样的:

for (size_t i = n; i --> 0 ;)

它有一个),没有搞笑的 1 ,B)的条件检查助记符,三)用合适的笑脸结束。

It has a) no funny -1, b) the condition check is mnemonic, c) it ends with a suitable smiley.

这篇关于反向迭代的无符号循环变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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