How to Access Global Variable if there is a Local Variable with Same Name in C/ C++? Last Updated : 23 Jul, 2025 Comments Improve Suggest changes 106 Likes Like Report Local Variable: The variable whose scope lies inside a function or a block in which they are declared. Global Variable: The variable that exists outside of all functions. It is the variable that is visible from all other scopes. We can access global variable if there is a local variable with same name in C and C++ through Extern and Scope resolution operator respectively. In C: 1) We can access a global variable if we have a local variable with same name in C using extern. C // C Program to demonstrate that we can access a global // variable if we have a local variable with same name #include <stdio.h> // 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; } OutputValue of global x is 50 Value of local x is 10 Time Complexity: O(1) Auxiliary Space: O(1) In C++: 2) We can access a global variable if we have a local variable with the same name in C++ using Scope resolution operator (::). 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 <iostream> 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; } OutputValue of global x is 50 Value of local x is 10 Time Complexity: O(1) Auxiliary Space: O(1) Create Quiz Comment K kartik Follow 106 Improve K kartik Follow 106 Improve Article Tags : C++ Explore C++ BasicsIntroduction to C++3 min readData Types in C++6 min readVariables in C++4 min readOperators in C++9 min readBasic Input / Output in C++3 min readControl flow statements in Programming15+ min readLoops in C++7 min readFunctions in C++8 min readArrays in C++8 min readCore ConceptsPointers and References in C++5 min readnew and delete Operators in C++ For Dynamic Memory5 min readTemplates in C++8 min readStructures, Unions and Enumerations in C++3 min readException Handling in C++12 min readFile Handling in C++8 min readMultithreading in C++8 min readNamespace in C++5 min readOOP in C++Object Oriented Programming in C++8 min readInheritance in C++6 min readPolymorphism in C++5 min readEncapsulation in C++3 min readAbstraction in C++4 min readStandard Template Library(STL)Standard Template Library (STL) in C++3 min readContainers in C++ STL2 min readIterators in C++ STL10 min readC++ STL Algorithm Library3 min readPractice & ProblemsC++ Interview Questions and Answers1 min readC++ Programming Examples4 min read Like