在倒数计数循环中使用size_t时的无限循环 [英] Infinite loop when using size_t in a count down for loop
本文介绍了在倒数计数循环中使用size_t时的无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我在任何索引for循环中都使用 size_t
而不是 int
来防止出现负索引.但是,当递减计数时,会导致溢出:
So I'm using size_t
instead of int
in any indexing for loop to prevent negative indices. But when counting down, this leads to an overflow:
for (size_t i = 10; i >= 0; --i) {
// Do something, f.ex. array[i] = i
}
预防这种情况的一种好方法是什么?
What would be a nice way to prevent this?
- 改为使用
int
? - 使用i == 0作为终止条件吗?(但是,如果我需要0,这将不起作用)
感谢您的反馈!
推荐答案
for (size_t i = 10; i <= 10; --i) // do something
当确实发生溢出时,它将四舍五入到最大整数,因此条件将失败.
When overflow do happens, it will round to the largest integer and thus the condition will fail.
这篇关于在倒数计数循环中使用size_t时的无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文