【问题标题】:C++ Confusing scope of redeclared variables in for loopC ++混淆for循环中重新声明变量的范围
【发布时间】:2016-10-22 12:28:39
【问题描述】:

下面的 while 循环不会终止。这是因为变量x 在while 循环中被重新声明。但我不明白为什么在第二次迭代中,语句x<10y=x 考虑了在外部范围中定义的x,而不是在以下语句中的块范围中定义的x。 这是因为一旦第一次迭代结束,块作用域中定义的x 就被破坏了,循环开始重新执行?

#include<iostream>
int main () {
  int x = 0, y;  
  while(x <10 ){
    y = x;
    std::cout<<"y is :"<< y <<std::endl;  
    int x = y + 1;
    std::cout<<"x is :"<< x <<std::endl;  
  }
  std::cout<<"While loop is over"<<std::endl;
}

【问题讨论】:

    标签: c++ while-loop scope redeclaration


    【解决方案1】:

    是的,你理解正确。所以每次在while比较时,都是使用外层x

    while (x < 10) {
        y = x; //Here the x is the outer one. The inner one does not exist yet.
        std::cout << "y is :" << y << std::endl;  
        int x = y + 1; // From here, x will refer to the inner one.
        std::cout << "x is :" << x << std::endl;  
        // inner x is destroyed.
    }
    

    【讨论】:

      【解决方案2】:

      while 循环每次迭代都会评估外部范围 x,并且 y 被分配外部范围 x 的值。之后在内部范围内定义另一个x,这是第二个std::cout 使用的,但程序没有使用内部x

      在下面的代码中,我用z 替换了内部x,但其他行为是相同的。唯一的区别是在更内部的范围内没有第二个x 来隐藏外部:

      #include<iostream>
      
      int main () {
          int x = 0, y;
          while(x <10 ){
              y = x;
              std::cout<<"y is :"<< y <<std::endl;
              int z = y + 1;
              std::cout<<"z is :"<< z <<std::endl;
          }
          std::cout<<"While loop is over"<<std::endl;
      }
      

      下面我有一个旨在消除混淆的示例。在内部范围内x 没有被“重新声明”,一个新的x 被声明并且在} 之后超出范围:

      #include<iostream>
      
      int main () {
          int x = 1;
          {
              int x = 2;
              std::cout << x << '\n'; // 2
          }
          std::cout << x << '\n'; // 1
      }
      

      【讨论】:

        猜你喜欢
        • 2011-05-27
        • 1970-01-01
        • 2011-12-06
        • 1970-01-01
        • 2015-11-29
        • 1970-01-01
        • 1970-01-01
        • 2018-05-13
        • 2015-09-12
        相关资源
        最近更新 更多