替代 for 循环语法 [英] Alternative for-loop syntax
问题描述
以下是 C 标准的片段(的第 6.8.5 节)n1256 TC3 C99).
Below is a snippet of the C standard(section 6.8.5 of the n1256 TC3 C99).
迭代语句:
while ( 表达式 ) 语句
do 语句 while ( 表达式 ) ;
for ( expressionopt ; expressionopt ; expressionopt ) 语句
for ( 声明 表达式opt ; 表达式opt ) 语句
iteration-statement:
while ( expression ) statement
do statement while ( expression ) ;
for ( expressionopt ; expressionopt ; expressionopt ) statement
for ( declaration expressionopt ; expressionopt ) statement
引起我兴趣的是最后一个语句:for ( declaration expression ; expression ) statement
.6.8.5.1 解释了 for
循环,但只提到了 for ( clause-1 ; expression-2 ; expression-3 ) 语句
语法.
What piques my interest is the last statement: for ( declaration expression ; expression ) statement
. 6.8.5.1 explains the for
loop, but only mentions the for ( clause-1 ; expression-2 ; expression-3 ) statement
syntax.
我曾尝试根据此语法编写代码,但它们都给了我语法错误.示例:
I did a few attempts at writing code according to this syntax, but they all gave me syntax errors. Examples:
for (int i = 0, i; i++) { /* ... */ }
for (int i = 0; !(i++)) { /* ... */ }
当使用 GCC(v4.9.2) 编译时,所有这些都会导致类似于 error: expected ‘;’ before ‘)’ token
的错误.
Which all results in errors similar to error: expected ‘;’ before ‘)’ token
when compiled using GCC(v4.9.2).
我不确定我是否以正确的方式解释了标准.可以以某种有用的方式使用此语法,还是我忽略了什么?
I'm not sure if I'm interpreting the standard in the right way. Can this syntax be used in some useful way, or have I overlooked something?
推荐答案
如果你看到,语法是,
for ( declaration expression1opt ; expression2opt ) statement
让我们将其与一般陈述进行比较
Let's compare it with a general statement
for (int i = 0; i < 10; i++) printf("%d ", i);
这里,
int i = 0;
表示declaration
[包括;
]i <10
表示expression1opt
[可选];
符合;
的语法要求[必须,如语法所述]i++
是expression2opt
[可选]printf("%d ", i);
是语句
int i = 0;
denotesdeclaration
[includes the;
]i < 10
denotesexpression1opt
[optional];
is as per the syntax requirement of;
[must, as described in syntax]i++
is theexpression2opt
[optional]printf("%d ", i);
is thestatement
现在,就你而言,
for (int i = 0, i; i++) { /* ... */ }
int i = 0, i;
表示声明
i++
表示expression1opt
;
缺失 .....int i = 0, i;
denotesdeclaration
i++
denotesexpression1opt
;
is missing .....
这里的最后一点产生了错误.您需要有 ;
才能通过语法检查.
The last point here produces the error. You need to have the ;
to pass the syntax check.
这篇关于替代 for 循环语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!