tags:

views:

284

answers:

2

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...

+8  A: 
for (int i = 0; ...)

is a C99 extension; in order to use it you must enable via specific compiler flags (at least in gcc). The C89 version is:

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

EDIT

Historically 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 rewrited as:

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

a block is defined as:

block := '{' declarations statements '}'

C99, C++, C# and Java allow to declare variables also in the middle of 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.

dfa
add -std=c99 to your compile command to enable the C99 dialect.
Jasarien
gcc doesn't quite implement all of C99. All of the important stuff is there (including this extension) but since it's not 100% implemented yet, it's not the default. The default with gcc is called "gnu89" which is C90 with some GNU extensions (some of which are the same as C99 extensions)
Tyler McHenry
Thanks for the EDIT!
Midnight Blue
+2  A: 

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.

AProgrammer