Since C99, you can declare automatic variables in any scope, including nested block scopes like the one you show.
However, the variable declared only exists inside that scope. At the closing brace ... it vanishes.
So, the reason you get an undeclared identifier error in the while
statement is that the identifier ceased existing at the }
immediately before the while
.
For reference:
void foo(int a) /* a will exist for the entire body of the function */
{
int b = 2 * a; /* so will b */
/* c is introduced at the start of the for statement ... */
for (int c = a; c < b; ++c)
{
int d = c; /* d is initialized and destroyed on each iteration */
} /* ... but c lasts until the end of the whole for statement,
which is here */
do
{ /* d will be initialized on every iteration */
int d = bar(); /* just like the (unrelated) d in our for loop above */
} /* and disappear at the end of each iteration */
while (d != a); /* ERROR - d doesn't exist here */
} /* a and b finally go out of scope */
FYI. in C89 - 99, you had to declare variables at the start of a block scope (typically the top-level function scope), after the opening {
but before any other statements. This isn't true any more, but you may still see old code in the old style.