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);