Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
160 views
in Technique[技术] by (71.8m points)

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

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...