📌  相关文章
📜  如果 C/C++ 中存在同名的局部变量,如何访问全局变量?

📅  最后修改于: 2022-05-13 01:54:41.900000             🧑  作者: Mango

如果 C/C++ 中存在同名的局部变量,如何访问全局变量?

局部变量:作用域位于声明它们的函数或块内的变量。

全局变量:存在于所有函数之外的变量。它是从所有其他范围可见的变量。

如果 C 和 C++ 中存在同名的局部变量,我们可以分别通过ExternScope 解析运算符访问全局变量。

在 C 中:

1)如果我们在 C 中有一个同名的局部变量,我们可以访问一个全局变量 外部

C
// C Program to demonstrate that we can access a global
// variable if we have a local variable with same name
#include 
  
// Global variable x
int x = 50;
  
int main()
{
    // Local variable x
    int x = 10;
    {
        extern int x;
        printf("Value of global x is %d\n", x);
    }
    printf("Value of local x is %d\n", x);
    return 0;
}


C++
// C++ Program to demonstrate that We can access a global
// variable if we have a local variable with same name in
// C++ using Scope resolution operator (::)
#include 
using namespace std;
  
// Global variable x
int x = 50;
  
int main()
{
    // Local variable x
    int x = 10;
    cout << "Value of global x is " << ::x << endl;
    cout << "Value of local x is " << x;
    getchar();
    return 0;
}


输出
Value of global x is 50
Value of local x is 10

在 C++ 中:

2)如果我们在 C++ 中有一个同名的局部变量,我们可以使用Scope 解析运算符(::) 访问一个全局变量。

C++

// C++ Program to demonstrate that We can access a global
// variable if we have a local variable with same name in
// C++ using Scope resolution operator (::)
#include 
using namespace std;
  
// Global variable x
int x = 50;
  
int main()
{
    // Local variable x
    int x = 10;
    cout << "Value of global x is " << ::x << endl;
    cout << "Value of local x is " << x;
    getchar();
    return 0;
}
输出
Value of global x is 50
Value of local x is 10