inner loop with same variable name as outer loop

2019-02-23 16:03发布

问题:

assuming the following simple code:

for(int i=0; i < 1000; i++)
{
  cout << "Outer i: " << i << endl;
  for(int i=0; i < 12; i++)
  {
    cout << "Inner i:" << i << endl;
  }
}

Works very nice. The same variable name in both loops used and the output is fine.

Do I understand it right that both variables are created on stack, and when the outer loop comes to the new inner loop, a new "namespace" (maybe the wrong name..) is created? But why is it overwritten? If I choose another name for the variable in inner loop I can also access the i from outer loop.

A bit confused I am.

回答1:

"Namespace" is kinda close.. but it is more about scope. The inner i hides/surpresses the outer i. You could think of another example:

{ 
 int i=0; //outer scope i.
 {
   int i =0; //this hides the outer scope i.. I can't use outer i here

 }
  i =1 ; //inner i is out of scope.. outer i is set to 1
}


回答2:

Your understanding is correct. The code is technically valid. However, this practice has many problems and is therefore a bad idea.

Each for loop has a separate scope associated with it. The variable declared in the inner loop shadows the variable declared in the outer loop. There is no way to access the outer i from the inner loop.