哪些版本的 C 允许您在 for 循环中声明变量?

What versions of C allow you to declare variables in for loops?

自从我开始用 C 编写代码以来,我就被教导

for(int i=0;i<10;++i)
...

在 C++ 中有效,但在 C 中,您必须像这样在 for 循环之外声明变量:

int i;
for(i=0;i<10;++i)
...

特别记得这是一个问题,因为当我开始用 C 编写代码时,我习惯了 C++ for 循环。

但今天我正在阅读 2010 年 12 月的 C11 标准草案,它将 for 循环定义为

"for ( clause-1 ; expression-2 ; expression-3 ) statement"

并且在它的语法描述中指出:

"如果子句 1 是 声明 ,它声明的任何标识符的范围是声明的其余部分,并且 整个循环”。

然后我做了一个测试,发现我的 gcc (Debian 8.3.0) 在 -std=c99 和 -std=c11 模式下以 C++ 风格编译循环,即使使用 -Wall 标志也没有警告.

这是一个 gcc 扩展,还是 C 支持这种循环有一段时间了,我只是没注意到?

它在 C99 中被标准化

来自:https://en.cppreference.com/w/c/language/for

(C99) If it is a declaration, it is in scope in the entire loop body, including the remainder of init_clause, the entire cond_expression, the entire iteration_expression and the entire loop_statement. Only auto and register storage classes are allowed for the variables declared in this declaration.