[英]Program stuck in Infinite loop
On the 2nd and subsequent iterations of the outer while
loop, space
will be initialized with a non-zero value, and then the while(space)
loop will keep incrementing space
for a long time until it overflows to a negative value, and then keep looping for a long time further until space
eventually increments to 0, finally breaking the loop.在外层
while
循环的第2次及后续迭代中, space
会被初始化为一个非零值,然后while(space)
循环会长时间保持递增space
,直到溢出为负值,然后保持进一步循环很长时间,直到space
最终增加到 0,最终打破循环。 When an int
is evaluated as a boolean, only 0 evaluates as false, all other values evaluate as true.当一个
int
被评估为 boolean 时,只有 0 被评估为 false,所有其他值被评估为 true。 And a 32bit int
can hold 4294967296 unique values (-2147483648..2147483647), giving the illusion that your loop is infinite.一个 32 位的
int
可以保存 4294967296 个唯一值(-2147483648..2147483647),给人一种循环是无限的错觉。
while(space)
{
std::cout << ' ';
space = space + 1;
}
When space
is 1
, this loop will increment i
, so it keeps looping.当
space
为1
时,此循环将增加i
,因此它会继续循环。 It will loop until space
overflow, and increment until space
is 0
它将循环直到
space
溢出,并递增直到space
为0
You probably want:你可能想要:
while(space)
{
std::cout << ' ';
--space;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.