First, this is absolutely legal: the code will compile and run, repeating the body of the nested loop 10×10=100 times. Loop counter i
inside the nested loop will hide the counter of the outer loop, so the two counters would be incremented independently of each other.
Since the outer i
is hidden, the code inside the nested loop's body would have access only to the value of i
of the nested loop, not i
from the outer loop. In situations when the nested loop does not need access to the outer i
such code could be perfectly justifiable. However, this is likely to create more confusion in its readers, so it's a good idea to avoid writing such code to avoid "maintenance liabilities."
Note: Even though the counter variables of both loops have the same identifier i
, they remain two independent variables, i.e. you are not using the same variable in both loops. Using the same variable in both loops is also possible, but the code would be hard to read. Here is an example:
for (int i = 1 ; i < 100 ; i++) {
for ( ; i % 10 != 0 ; i++) {
printf("%02d ", i);
}
printf("%d\n", i);
}
Now both loops use the same variable. However, it takes a while to figure out what this code does without compiling it (demo);
i
, with different scopes. Use-Wshadow
with GCC to get such problems reported automatically.-Wshadow
is not included in-Wall
.-Wshadow
warns about shadowing of global variables as well, which could easily get annoying in larger projects.-Wextra
does not include-Wshadow
. I guess it is common enough in some projects, or some gcc developer loves shadowing as a coding style, to warrant being left out like this.-Wshadow
has a horrendous false positive rate, rendering it completely useless. Scope exists for a reason, and shadowing is a priori not problematic. Now-Wshadow-local
(note: not-Wshadow=local
) is very different. But unfortunately GCC has so far refused to include it in trunk (though there appear to be forks of GCC which do include it).