替代for循环的语法 [英] Alternative for-loop syntax

查看:106
本文介绍了替代for循环的语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是C标准的片段的的(第6.8.5 n1256 TC3 C99)。

Below is a snippet of the C standard(section 6.8.5 of the n1256 TC3 C99).

循环语句:的结果
       ,而 前pression 语句结果
       语句,而 前pression ;结果
       前pression 选择 的;的前pression 选择 的;的前pression 选择 语句结果
       声明前pression 选择 ; 前pression 选择 语句

iteration-statement:
    while ( expression ) statement
    do statement while ( expression ) ;
    for ( expressionopt ; expressionopt ; expressionopt ) statement
    for ( declaration expressionopt ; expressionopt ) statement

什么激起了我的兴趣是最后的语句:为(申报前pression;前pression)语句。 6.8.5.1说明循环,但只提到了的(第1;前pression-2;前pression -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.

我没有在写作code几次尝试按照这种语法,但他们都让我的语法错误。例如:

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)编译

Which all results in errors similar to error: expected ‘;’ before ‘)’ token when compiled using GCC(v4.9.2).

我不知道如果我间preting以正确的方式的标准。可在此语法一些有用的方式来使用,或者有我忽略的东西吗?

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 \t", i);

在这里,


  • INT I = 0; 表示声明 [包括; ]

  • I&LT; 10 表示前pression1opt [可选]

  • ; 是根据的语法要求; [绝,如语法描述]

  • 我++ 前pression2opt [可选]

  • 的printf(%d个\\ t的,我); 语句

  • int i = 0; denotes declaration [includes the ;]
  • i < 10 denotes expression1opt [optional]
  • ; is as per the syntax requirement of ; [must, as described in syntax]
  • i++ is the expression2opt [optional]
  • printf("%d \t", i); is the statement

现在,你的情况,

for (int i = 0, i; i++) { /* ... */ }


  • INT I = 0,I; 表示声明

  • 我++ 表示前pression1opt

  • ; 丢失的.....

    • int i = 0, i; denotes declaration
    • i++ denotes expression1opt
    • ; is missing .....
    • 最后一点,在这里产生错误。你需要有; 来通过语法检查

      The last point here produces the error. You need to have the ; to pass the syntax check.

      这篇关于替代for循环的语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆