Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
528 views
in Technique[技术] by (71.8m points)

c++ - inner loop with same variable name as outer loop

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

"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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...