在 for 循环中迭代所有无符号整数 [英] Iterating over all unsigned integers in a for loop
问题描述
假设我想在 for
循环中遍历所有整数.为了便于讨论,假设我正在为每个整数调用一些未知函数 f(unsigned x)
:
Let's say I want to iterate over all integers in a for
loop. For the sake of discussion, assume I am calling some unknown function f(unsigned x)
for each integer:
for (unsigned i = 0; i < UINT_MAX; i++) {
f(i);
}
当然,上面没有遍历所有整数,因为它错过了一个:UINT_MAX.将条件更改为 i <= UINT_MAX
只会导致无限循环,因为这是同义反复.
Of course, the above fails to iterate over all integers, because it misses one: UINT_MAX. Changing the condition to i <= UINT_MAX
just results in an infinite loop, because that's a tautology.
您可以使用 do-while
循环来实现,但是您会失去 for
语法的所有细节.
You can do it with a do-while
loop, but you lose all the niceties of the for
syntax.
我可以吃蛋糕(for
循环)并吃掉它(迭代所有整数)吗?
Can I have my cake (for
loops) and eat it too (iterate over all integers)?
推荐答案
你可以用 do-while 循环来做,但是你失去了所有的细节for 语法.
You can do it with a do-while loop, but you lose all the niceties of the for syntax.
通过使用匿名块作用域,它仍然可以使用 do-while 循环:
It is still doable with do-while loop by using an anonymous block scope:
{
unsigned i = 0;
do { f(i); } while (++i != 0);
}
虽然这个结构可能不是最惯用的,但它显然是清晰的汇编代码的候选者.例如,gcc -O
将其编译为:
While this construct may not be most idiomatic, it is an obvious candidate for clear assembly code. For example, gcc -O
compiles it as:
.L2:
mov edi, ebx ; ebx starts with zero
call f
add rbx, 1
cmp rbx, rbp ; rbp is set with 4294967296
jne .L2
这篇关于在 for 循环中迭代所有无符号整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!