C: for loop int initial declaration

Can someone elaborate on 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);        
    }
}

P.S: I vaguely recall that int i should be declared before a for loop. I should state that I am looking for an answer that gives a historical context of C standard.


Solution 1:

for (int i = 0; ...) 

is a syntax that was introduced in C99. In order to use it you must enable C99 mode by passing -std=c99 (or some later standard) to GCC. The C89 version is:

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

EDIT

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

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

must be rewritten as:

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

a block is defined as:

block := '{' declarations statements '}'

C99, C++, C#, and Java allow declaration of variables anywhere in a block.

The real reason (guessing) is about allocating internal structures (like calculating stack size) ASAP while parsing the C source, without go for another compiler pass.

Solution 2:

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