PSkocik PSkocik - 3 months ago 19
C Question

Two-part for loop in C


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?


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