C ++混淆for循环中重新声明变量的范围

C++ Confusing scope of redeclared variables in for loop

下面的 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;
}

while 循环的每次迭代都会计算外部作用域 x,并且 y 被赋予外部作用域 x 的值。在那之后,另一个 x 被定义在第二个 std::cout 所使用的内部范围内,但是程序没有使用内部 x

在下面的代码中,我将内部的 x 替换为 z,但其他方面的行为是相同的。唯一的区别是在更内部的范围内没有第二个 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 不是 "re-declared",正在声明一个新的 x 并且它在 }:

之后超出范围
#include<iostream>

int main () {
    int x = 1;
    {
        int x = 2;
        std::cout << x << '\n'; // 2
    }
    std::cout << x << '\n'; // 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.
}