Skip to content
Related Articles

Related Articles

How to access global variable if there is a local variable with same name in C/ C++
  • Difficulty Level : Easy
  • Last Updated : 19 Apr, 2021

we can access a global variable if we have a local variable with same name in C using extern.

C




// C Implementation
#include <stdio.h>
 
int x = 50; // Global x
 
int main()
{
    int x = 10; // Local x
    {
        extern int x;
        printf("Value of global x is %d\n", x);
    }
    printf("Value of local x is %d\n", x);
    return 0;
}
Output
Value of global x is 50
Value of local x is 10

we can access a global variable if we have a local variable with same name in C++ using scope resolution operator (::)

C++




// C++ Implementation
#include <iostream>
 
using namespace std;
 
int x = 50; // Global x
 
int main()
{
    int x = 10; // Local x
    cout << "Value of global x is " << ::x << endl;
    cout << "Value of local x is " << x;
    getchar();
    return 0;
}
Output
Value of global x is 50
Value of local x is 10

 

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.



My Personal Notes arrow_drop_up
Recommended Articles
Page :