替代for循环语法
以下是C标准的一小部分( n1256 TC3 C99的第6.8.5节)。
迭代语句:
while ( expression式 ) 语句
( expression ) ;
用于 ( expression式opt ; expression式opt ; expression式opt ) 语句
用于 ( 声明 expression式opt ; expression式opt ) 语句
我最感兴趣的是最后一个陈述:( for ( declaration expression ; expression ) statement 。 6.8.5.1解释了for循环,但只提到了for ( clause-1 ; expression-2 ; expression-3 ) statement语法。
我按照这个语法写了一些代码,但都给了我语法错误。 例子:
for (int i = 0, i; i++) { /* ... */ } for (int i = 0; !(i++)) { /* ... */ }
所有导致错误类似的error: expected ';' before ')' token 使用GCC(v4.9.2)进行编译时, error: expected ';' before ')' token 。
我不确定是否以正确的方式解释标准。 这个语法可以用一些有用的方法,还是我忽略了一些东西?
如果你看到,语法是,
for ( declaration expression1opt ; expression2opt ) statement
我们将其与一般性陈述进行比较
for (int i = 0; i < 10; i++) printf("%d \t", i);
这里,
-
int i = 0;表示declaration[包括;] -
i < 10表示expression1opt[可选] -
;是按照语法要求的;[必须,如语法所述] -
i++是expression2opt[可选] -
printf("%d \t", i);是statement
现在,在你的情况下,
for (int i = 0, i; i++) { /* ... */ }
-
int i = 0, i;表示declaration -
i++表示expression1opt -
;失踪 …..
最后一点产生错误。 你需要有; 通过语法检查。
不幸的是,这不容易阅读。 你错误地理解了陈述的第二个案例。 第一个分号是declaration一个组成部分,因此隐藏在你的眼睛里。 您可以通过查看附录A来轻松查看这些语法问题。您可以:
(6.7) declaration: declaration-specifiers init-declarator-listopt ; static_assert-declaration