问题描述
为什么下面的c代码以无限循环结尾?
Why does the following c code end up in an infinite loop?
for(unsigned char i = 0; i <= 0xff; i++){}
与以下结果相同:
for(unsigned char i = 0; i <= 0xff; ++i){}
我必须以哪种方式修改代码,以使其按预期工作(不使用int
或unsigned int
数据类型)?
In which way do I have to modify the code, to get it working as expected (without using int
or unsigned int
datatype)?
推荐答案
典型的for
循环依赖于能够在循环的最后迭代之后 检测终止条件.在您的情况下,正如其他答案所指出的那样,i <= 0xff
始终为真(假定i
的类型为unsigned char
且通常为UCHAR_MAX==0xff
).
A typical for
loop relies on being able to detect the termination condition after the last iteration of the loop. In your case, as other answers have pointed out, i <= 0xff
is always true (given that i
is of type unsigned char
and that UCHAR_MAX==0xff
, which is typical).
您可能会在任何整数类型的边界附近遇到相同类型的问题.例如,这:
You can run into the same kind of problem near the bounds of any integer type. For example, this:
for (int i = INT_MAX - 9; i <= INT_MAX; i ++) {
/* ... */
}
(可能)也是一个无限循环(除了有符号整数类型的溢出具有未定义的行为,而与无符号整数的定义明确的环绕语义相反,优化的编译器可以利用这一点,但我离题了) ).只是不要这样做.
is (probably) also an infinite loop (except that overflow for signed integer types has undefined behavior as opposed to the well-defined wraparound semantics for unsigned integers, and an optimizing compiler can take advantage of that and -- but I digress). Just don't do that.
许多解决方案之一是将测试移到循环的底部,然后递增:
One of many solutions is to move the test to the bottom of the loop, before the increment:
for (unsigned char i = 0; ; i ++) {
printf("%d\n", i);
if (i == 0xff) break;
}
for
循环的第二个子句是终止条件,在每次迭代之前进行评估.如果将其保留为空,它将一如既往地为您提供无限循环(for (;;)
是简单无限循环的常见用法).我们在循环的底部测试i
是否与0xff
相等.如果是,那么我们就执行了最后一次迭代,就可以跳出循环了.
The second clause of a for
loop is the termination condition, evaluated before each iteration. If you leave it empty, it's treated as always true, giving you an infinite loop (for (;;)
is a common idiom for a simple infinite loop). We test whether i
is equal to 0xff
at the bottom of the loop. If it is then we've just executed the last iteration, and we can break out of the loop.
(有些人可能更喜欢在这里使用while
循环,但我喜欢for
,因为它使我们可以将循环控制变量的声明和增量结合在一个结构中.)
(Some might prefer to use a while
loop here, but I like the for
because it lets us combine the declaration of the loop control variable and the increment in a single construct.)
(严格来说,unsigned char
的最大值不一定是0xff
或255
,但是它将出现在您可能会遇到的任何系统上.某些DSP的实现具有CHAR_BIT > 8
,因此UCHAR_MAX > 255
.)
(Strictly speaking the maximum value of unsigned char
isn't necessarily 0xff
or 255
, but it will be on any system you're likely to encounter. Implementations for some DSPs have CHAR_BIT > 8
, and thus UCHAR_MAX > 255
.)
这篇关于for(unsigned char i = 0; i <= 0xff; i ++)产生无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!