C: for initial declaration of int loop

Can someone clarify the following gcc error?

$ gcc -o Ctutorial/temptable.out temptable.c temptable.c: In function 'main': temptable.c:5: error: 'for' loop initial declaration used outside C99 mode 

temptable.c:

 ... /* print Fahrenheit-Celsius Table */ main() { for(int i = 0; i <= 300; i += 20) { printf("F=%d C=%d\n",i, (i-32) / 9); } } 

PS: I vaguely remember that int i must be declared before the for loop. I must indicate that I am looking for an answer that gives the historical context of standard C.

+28
c gcc for-loop syntax-error
Aug 17 '09 at 13:07
source share
2 answers
 for (int i = 0; ...) 

is the syntax that was introduced in C99. To use it, you must enable C99 mode by passing -std=c99 (or some later standard) to GCC. C89 Version:

 int i; for (i = 0; ...) 

EDIT

Historically, C has always forced programmers to declare all variables at the beginning of a block. So something like:

 { printf("%d", 42); int c = 43; /* <--- compile time error */ 

need to rewrite as:

 { int c = 43; printf("%d", 42); 

a block is defined as:

 block := '{' declarations statements '}' 

C99, C ++, C #, and Java allow variable declarations anywhere in the block.

The real reason (guessing) is the distribution of internal structures (for example, calculating the stack size) of the ASAP when analyzing the source C, without going to another compiler pass.

+59
Aug 17 '09 at 13:08
source share
β€” -

Before C99, you had to define local variables at the beginning of the block. C99 imported a C ++ function that allows you to mix local variable definitions with instructions, and you can define variables in control expressions for and while .

+8
Aug 17 '09 at 13:09
source share



All Articles