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

Uclydde picture Uclydde · Jul 27, 2018 · Viewed 13.1k times · Source

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

Or will the variables affect each other? Should the following code use a different variable for the second loop, such as j, or is i fine?

for(int i = 0; i < 10; i++)
{
  for(int i = 0; i < 10; i++)
  {
  }
}

Answer

Eric Postpischil picture Eric Postpischil · Jul 27, 2018

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.