具有与外部循环相同的变量名的内部循环 [英] inner loop with same variable name as outer loop

查看:380
本文介绍了具有与外部循环相同的变量名的内部循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设以下简单代码:

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.

我是否正确地理解两个变量都是在堆栈上创建的,并且当外循环进入新的内循环时,会创建一个新的命名空间"(也许是错误的名称..)吗?但是为什么它会被覆盖呢?如果在内部循环中为变量选择另一个名称,我也可以从外部循环访问i.

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.

我有点困惑.

推荐答案

命名空间"有点接近..但是它更多地是关于范围的.内层i 隐藏/抑制外层i.您可能会想到另一个示例:

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

这篇关于具有与外部循环相同的变量名的内部循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆