C++ if 语句中奇怪的范围

sli*_*uat 0 c++ scope

当我在 if 语句内声明任何内容时,它不会从其中传播出来,此外,如果我在外部有一个变量,并且我在 if 语句内重新声明它,一旦代码结束该语句,它就会丢失它,我如何才能设法全球化if 语句的范围。

Nin*_*rry 5

在内部作用域中重新声明变量会创建一个新变量。

#include <iostream>

int main()
{
    int i = 1;

    if (true)
    {
        int i = 42;  // variable is re-declared
    } // lifetime of inner i ends here

    std::cout << i; // expected output 1  
    
}
Run Code Online (Sandbox Code Playgroud)

您可以在内部作用域中引用在外部声明的变量,而无需重新声明它。

#include <iostream>

int main()
{
    int i = 1;

    if (true)
    {
        i = 42;  // variable from outer scope is used
    }

    std::cout << i; // expected output 42  
    
}
Run Code Online (Sandbox Code Playgroud)