Names denoted the same entity

拈花ヽ惹草 提交于 2019-12-01 22:29:31

The potential scope of a variable declared at the file scope (i.e., not inside a namespace, class, or function) is from the point at which the variable is declared until the end of file. The potential scope of a variable declared inside a function is from the point at which the variable is declared until the close brace inside of which the variable was declared.

The actual scope of a variable can be smaller than the potential scope if a new variable of the same name is declared at some inner scope. This is called shadowing.

// The following introduces the file scope variable j.
// The potential scope for this variable is from here to the end of file.
int j = 42; 

// The following introduces the file scope variable k.
int k = 0;

// Note the parameter 'j'. This shadows the file scope 'j'.
void foo (int j) 
{
    std::cout << j << '\n'; // Prints the value of the passed argument.
    std::cout << k << '\n'; // Prints the value of the file scope k.
}
// The parameter j is out of scope. j once again refers to the file scope j.


void bar ()
{
    std::cout << j << '\n'; // Prints the value of the file scope j.
    std::cout << k << '\n'; // Prints the value of the file scope k.

    // Declare k at function variable, shadowing the file scope k.
    int k = 1; 
    std::cout << k << '\n'; // Prints the value of the function scope k.

    // This new k in the following for loop shadows the function scope k.
    for (int k = 0; k < j; ++k) { 
        std::cout << k << '\n'; // Prints the value of the loop scope k.
    }
    // Loop scope k is now out of scope. k now refers to the function scope k.

    std::cout << k << '\n'; // Prints the function scope k.
}
// Function scope k is out of scope. k now refers to the file scope k.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!