So currently as a the do while exists the body of the loop is a block:
do
{ // begin block
int i = get_data();
// whatever you want to do with i;
} //end block
while (i != 0);
so how does a block scope work, from section 3.3.3
Block scope:
A name declared in a block (6.3) is local to that block; it has block scope. Its potential scope begins at its
point of declaration (3.3.2) and ends at the end of its block. A variable declared at block scope is a local
variable.
So clearly the scope of i
is the block, so you want a rule that would create some sort of special do while block scope. How would that practically work? It would seem the simplest equivalent would be to hoist the declaration to a newly created outer block:
{
int i = get_data(); // hoist declaration outside
do
{ // begin block
// whatever you want to do with i;
} //end block
while (i != 0);
}
which could possibly work fine if all the declarations where at the start of the body, but what about a scenario like this:
int k = 0 ;
do
{
int i = get_data();
k++ ; // side effect before declaration
int j = k ; // j it set to 1
}
while (i != 0);
after hoisting:
int k = 0 ;
{
int i = get_data();
int j = k ; // j is set to 0
do
{
k++ ;
}
while (i != 0);
}
Another alternative would be to extend the scope from the do while onwards but that would break all sorts of expected behavior. It would break how name hiding works in block scope from section 3.3.10
Name hiding:
A name can be hidden by an explicit declaration of that same name in a nested declarative region or derived
class (10.2).
and example from 3.3.1
shows this:
int j = 24;
int main() {
int i = j, j;
j = 42;
}
the j
in main
hides the global j
but how would work for our special do while scope?:
int j = 24;
do {
int i = j, j;
j = 42;
} while( j != 0 )
Extending the scope of the inner j
from the do while forwards would surely break a lot of existing code and looking at the previous example there is no intuitive way to hoist the declaration out.
We could play with this an eventually and find something that works but it seems like a lot of work for very little gain and it is completely unintuitive.