Italo Grossi
Italo Grossi

Reputation: 95

Variable declaration on "start value" of FOR loop - What C standards allow it?

C Language

On which C Standard the following code compiles without error (C89, C99, C11)

for (int i = 0; i < 10; ++i) {

    DO SOMETHING...

}

I understand that some C compilers won't accept the version above and the variable "i" must be declare outside the parentheses. Like so:

int i;
for (i = 0; i < 10; ++i) {

    DO SOMETHING...

}

Upvotes: 1

Views: 1116

Answers (3)

Yu Hao
Yu Hao

Reputation: 122453

It's first introduced in C99. Quoting from C99 Rational V5.10 §6.8.5.3 The for statement

A new feature of C99:It is common for a for loop to involve one or more counter variables which are initialized at the start of the loop and never used again after the loop. In C89 it was necessary to declare those variables at the start ofthe enclosing block with a subsequent risk of accidentally reusing them for some other purpose. It is now permitted to declare these variables as part of the forstatement itself. Such a loop variable is in a new scope, so it does not affect any other variable with the same name and is destroyed at the end of the loop, which can lead to possible optimizations.

To simplify the syntax, each loop is limited toa single declaration (though this can declare several variables), and these must have autoor registerstorage class.

Example:

int i = 42;  15 
for (int i = 5, j = 15; i < 10; i++, j--) 
printf("Loop %d %d\n", i, j); 
printf("I = %d\n", i); // there is no j in scope

will output:

Loop 5 15  20 
Loop 6 14 
Loop 7 13 
Loop 8 12 
Loop 9 11 
I = 42  25 

Note that the syntax allows loops like:

for (struct s *p = list, **q; p != NULL; p = *q) 
q = &(p->next);

Upvotes: 7

ouah
ouah

Reputation: 145899

This is allowed since c99. So c99 and c11 support it.

In c89, the first clause of a for statement can only be an expression. In c99 and c11 it can be an expression or a declaration. Only one single declaration is allowed (though this can declare several variables).

Upvotes: 8

Cody Gray
Cody Gray

Reputation: 244843

C99 is when support for this first became part of the standard.

Basically, the for statement introduced an additional implicit block. All other block scoping rules remained the same.

You could simulate the same thing in pre-C99 implementations by introducing the additional block scope around the for loop yourself:

{
    int i;
    for (i = 0; i < 10; ++i)
    { ... }
}
{
    int i;  // i here is not the same as i up there
}

Upvotes: 4

Related Questions