Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two-part for loop in C [duplicate]

Tags:

c

c11

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

mentions

for ( declaration expression opt ; expression opt ) statement

under 6.8.5 Iteration statements.

Is this a typo or does C11 have a two-expressions-in-the-parens for loop?

like image 707
PSkocik Avatar asked Sep 26 '16 14:09

PSkocik


1 Answers

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

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

The 2nd version refers to the case where you declare loop iterator variables, new since C99.

Now if we look at what the syntax for declaration means, it is found 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 2nd version of the for loop and you get this:

for (declaration-specifiers init-declarator-listopt ; expressionopt ; expressionopt )
like image 76
Lundin Avatar answered Sep 19 '22 12:09

Lundin