如果条件未提供给 For 循环会怎样?

What happens if a conditional isn't supplied to a For Loop?

考虑这个片段:

int numbers[9] = {5, 2, 78, 23, 8, 9, 3, 12, 97};
int arrLength = (sizeof(numbers) / sizeof(int));

for(int i = 0; arrLength; i++) {
    printf("%d\n", numbers[i]);
}

我给了一个数组长度作为循环的第二个参数,但没有给出何时停止的条件。输出给出了我数组中的 9 个数字,然后继续。这是程序输出的示例。该程序以这种方式轻松输出超过 100 位数字。谁能解释一下是什么在起作用?

在这种情况下,条件

 for(int i = 0; arrLength; i++)

相同
for(int i = 0; arrLength != 0; i++)

换句话说,控制表达式(a.k.a。条件检查)应该评估为 TRUE 以继续执行循环体。

来自 C11,章节 6.8.5,P4

An iteration statement causes a statement called the loop body to be executed repeatedly until the controlling expression compares equal to 0. [...]

并且,脚注 158,for 循环

[...]the controlling expression, expression-2, specifies an evaluation made before each iteration, such that execution of the loop continues until the expression compares equal to 0; [...]

如果条件 未提供 ,则它被视为 non-zero(始终为真值)。

第 6.8.5.3 章第 2 段

Both clause-1 and expression-3 can be omitted. An omitted expression-2 is replaced by a nonzero constant.