Willis Hershey
Willis Hershey

Reputation: 1574

What versions of C allow you to declare variables in for loops?

Ever since I began coding in C, I was taught that

for(int i=0;i<10;++i)
...

worked in C++, but in C you must declare the variable outside of the for loop like so:

int i;
for(i=0;i<10;++i)
...

I specifically remember this being a problem because I was used to C++ for loops when I began coding in C.

But today I was reading the December 2010 draft of the C11 standard, and it defined the for loop as

"for ( clause-1 ; expression-2 ; expression-3 ) statement"

and in it's description of syntax it noted:

If clause-1 is a declaration, the scope of any identifiers it declares is the remainder of the declaration and the entire loop.

THEN I did a test and realized that my gcc (Debian 8.3.0) compiles for loops in the C++ style in -std=c99, AND in -std=c11 mode with no warnings even with the -Wall flag.

Is this a gcc extension, or has C supported this type of loop for a while and I just didn't notice?

Upvotes: 3

Views: 885

Answers (1)

Enosh Cohen
Enosh Cohen

Reputation: 399

It was standardized in C99

from: https://en.cppreference.com/w/c/language/for

(C99) If it is a declaration, it is in scope in the entire loop body, including the remainder of init_clause, the entire cond_expression, the entire iteration_expression and the entire loop_statement. Only auto and register storage classes are allowed for the variables declared in this declaration.

Upvotes: 11

Related Questions