Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative for-loop syntax [duplicate]

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

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

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++)) { /* ... */ } 

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?

like image 875
bzeaman Avatar asked Dec 10 '14 10:12

bzeaman


People also ask

What can be used instead of for loop?

Array. filter, map, some have the same performance as forEach. These are all marginally slower than for/while loop. Unless you are working on performance-critical functionalities, it should be fine using the above methods.

What are the 3 types of loop statement?

Java provides three repetition statements/looping statements that enable programmers to control the flow of execution by repetitively performing a set of statements as long as the continuation condition remains true. These three looping statements are called for, while, and do… while statements.

Can we use while loop instead of for loop?

Use a for loop when you know the loop should execute n times. Use a while loop for reading a file into a variable. Use a while loop when asking for user input. Use a while loop when the increment value is nonstandard.


1 Answers

Unfortunately, this is not easy to read. You are misreading the second case of the for statement. The first semicolon is an integral part of declaration and thus hidden to your eyes. You can easily check such syntax questions by looking into Annex A. There you have:

(6.7) declaration:      declaration-specifiers init-declarator-listopt ;     static_assert-declaration 
like image 100
Jens Gustedt Avatar answered Oct 08 '22 03:10

Jens Gustedt