Two-section loop in C

http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf

mentions

for ( declaration expression opt ; expression opt ) statement 

6.8.5 Iteration operators .

Is this a typo or does C11 have a loop with two expressions in the columns for ?

+5
source share
2 answers

It is all about syntax. 6.8.5 gives two forms for loops:

 for ( expressionopt ; expressionopt ; expressionopt ) statement for ( declaration expressionopt ; expressionopt ) statement 

The second version refers to the case when you declare loop iterator variables new with C99.

Now, if we look at what the declaration syntax means, it is in 6.7:

 declaration: declaration-specifiers init-declarator-listopt ; 

Note the semicolon at the end - it requires a semicolon as part of the syntax. Copy / paste the syntax into the second version of the for loop and you will get the following:

 for (declaration-specifiers init-declarator-listopt ; expressionopt ; expressionopt ) 
+5
source

On the next page n1570 we see:

6.8.5.3 Statement

Statement
for ( clause-1 ; expression-2 ; expression-3 ) statement
...

and then this paragraph-1 may be a declaration or expression

And in 6.7 Dรฉclarations we can see:

Syntax
Ad:
Declaration-specifiers init-declarator-listopt;

I understand that part of the declaration includes the first semicolon. For example, in for(int i=0; i<10; i++)

  • int i=0; is an ad
  • i<10 is the first optional expression
  • i++ - second optional expression
+1
source

All Articles