Moving the kernel to modern C
Moving the kernel to modern C
Posted Mar 1, 2022 21:58 UTC (Tue) by nybble41 (subscriber, #55106)In reply to: Moving the kernel to modern C by ianmcc
Parent article: Moving the kernel to modern C
> In C++ the declaration and the body of the loop are the same scope.
for (init-statement condition[opt] ; expression) statement
The body of the for loop is just *statement*. If the declaration were in that scope it wouldn't survive from one iteration of the loop to the next or be visible in *condition* or *expression*. Declarations in *init-statement* are scoped over the entire for loop, not just the body.
Normally a compound statement within *statement* would introduce its own separate block scope *below* the level of *statement*, but in C++ the lines are blurred between the body of the for loop and the *inside* of the compound statement. In other words, I would expect this to be a redeclaration error, because `char i` and `int i` are declared in the same scope (note that all the examples in the standard are of this form):
for (int i = 0; i < N; ++i)
char i = 7;
but not this, because `char i` is declared in the new *nested* scope created by the compound statement and not directly in the body of the for loop:
for (int i = 0; i < N; ++i) {
char i = 7;
}
Contrast this with the following code which the standard (C++20 draft) claims is "equivalent" to the second example "except that names declared in the init-statement are in the same declarative region as those declared in the condition, and except that a continue in statement (not enclosed in another iteration statement) will execute expression before re-evaluating condition":
{
int i = 0; /* init-statement */
while (i < N /* condition */) {
{ char i = 7; } // statement
++i;
}
}
In the "equivalent" while loop version there is clearly no redeclaration error—the `char i` declaration is within not just one but two levels of compound statements under the while loop and the scope where `int i` was declared.
> After all, who would write such code anyway? Its a strange thing to take issue with.
Whether you would write that by hand or not, it's an unnecessary (and IMHO completely pointless) complication which moreover breaks compatibility with C. Redeclaration conflicts could appear as a result of macro expansion or other code generation, not just in hand-written code.
