How to access global variable if there is a local variable with same name in C/ C++
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 xint 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 xint 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



