Names denoted the same entity

前端 未结 1 1015
自闭症患者
自闭症患者 2021-01-20 20:30

The following definition of declarative region:

Every name is introduced in some portion of program text called a declarative region, which

1条回答
  •  再見小時候
    2021-01-20 21:03

    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.
    

    0 讨论(0)
提交回复
热议问题