访问嵌套块中重新定义的变量

Access to redefined variables inside a nested block

本文关键字:定义 变量 新定义 嵌套 访问      更新时间:2023-10-16

请考虑以下程序:

#include <iostream>
using std::cout;
int i = 10;
int main() {
     int i = 9;
     {
          int i = 8;
          {
                int i = 7;
                cout << i << "n";   // i = 7
                cout << ::i << "n"; // i = 10 (global i)
                // How could we access to other i declarations here?
          }
     }
     return 0;
}

在嵌套块中使用i引用i的最后一个声明,因为后者隐藏了其他声明。为了使用全局i(函数 main 之外的声明(,我们可以使用 ::i

我想知道是否有办法在嵌套块中使用i的其他十折

声明一个新的变量名称,类似于"j"而不是"i"。

#include <iostream>
using std::cout;
int i = 10;
int main() {
     int i = 9;
     {
          int j = 8;
          {
                int j = 7;
                cout << j << "n";   // j = 7
                cout << ::i << "n"; // i = 10 (global i)
                // How could we access to other 
       i declarations here?
          }
     }
     return 0;
    }