Can a 'for' loop inside of a 'for' loop use the same counter variable name?

Solution 1:

You may use the same name (identifier). It will be a different object. They will not affect each other. Inside the inner loop, there is no way to refer to the object used in the outer loop (unless you make special provisions for that, as by providing a pointer to it).

This is generally bad style, is prone to confusion, and should be avoided.

The objects are different only if the inner one is defined separately, as with the int i you have shown. If the same name is used without defining a new object, the loops will use the same object and will interfere with each other.

Solution 2:

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