3

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?

Willis Hershey
  • 1,520
  • 4
  • 22
  • 1
    It's the latter : ) – ikegami May 13 '20 at 04:09
  • You are likely to be one of the many victims of C teachers teaching on Windows as MSVC didn't support the quite old C99 for over a decade in "C mode" but did support the very same extensions to C89 in "C-++ mode", hence many having the view that you can't mix declarations and other statements in C etc. However, most of those quality-of-coding features are in C nowadays (well, for 20 years already) – ljrk May 13 '20 at 08:56
  • 2
    And lets not mention the severely incompetent teachers that still teaches MS DOS programming in Borland Turbo C to this day... – Lundin May 13 '20 at 09:11
  • And if you feel betrayed by that, also check out "compound literals". The truth will set you free. – bd2357 May 13 '20 at 23:07

1 Answers1

10

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.

Enosh Cohen
  • 369
  • 2
  • 11