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

c++ weird scope in if statement

当我在 if 语句中声明任何东西时,它不会传播出去,而且,如果我在外面有一个变量,我在 if 语句中重新声明它,一旦代码结束语句它就丢失了,怎么可能我设法将 if 语句的范围全球化。

在内部范围内重新声明一个变量会创建一个新变量。

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

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

#include <iostream>

int main()
{
    int i = 1;

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

    std::cout << i; // expected output 42  
    
}