Is the following code legal according to C99?
...
for(....) {
int x = 4;
...
}
...
You can assume that before line 3 the variable x was never declared.
Until now I have only found the following, but I dont think that this is enough:
A block allows a set of declarations and statements to be grouped into one syntactic unit. The initializers of objects that have automatic storage duration, and the variable length array declarators of ordinary identifiers with block scope, are evaluated and the values are stored in the objects (including storing an indeterminate value in objects without an initializer) each time the declaration is reached in the order of execution, as if it were a statement, and within each declaration in the order that declarators appear.
From page 145 of that PDF.
Yes, you can declare or define a variable anywhere you want in C99 (at the start of a block in C89).
You said:
"You can assume that before line 3 the variable x was never declared."
Even if it was previously declared, you could declare a new variable with the same name. Doing that prevents you from accessing the old variable within that block.
int x = 0; /* old x */
printf("%d\n", x); /* old x, prints 0 */
do {
int x = 42; /* new x */
printf("%d\n", x); /* new x, prints 42 */
} while (0);
printf("%d\n", x); /* old x, prints 0 */
I've never tried the following in C99. I really don't know what happens :)
I'll try later, when I get access to a (almost) C99 compiler
int x = 0;
do {
printf("%d\n", x); /* old x? new x? crash? Undefined Behaviour? */
int x = 42;
} while (0);
The C99 feature of declaring/defining variables wherever one wants is not a feature that makes me want to change :)