Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to access global variable if there is a local variable with same name in C/ C++

  • Difficulty Level : Basic
  • Last Updated : 19 Apr, 2021

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

Take a step-up from those "Hello World" programs. Learn to implement data structures like Heap, Stacks, Linked List and many more! Check out our Data Structures in C course to start learning today.

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

 




My Personal Notes arrow_drop_up