VOOZH about

URL: https://www.geeksforgeeks.org/cpp/how-to-access-global-variable-if-there-is-a-local-variable-with-same-name-in-c-cpp/

⇱ How to Access Global Variable if there is a Local Variable with Same Name in C/ C++? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Access Global Variable if there is a Local Variable with Same Name in C/ C++?

Last Updated : 23 Jul, 2025

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. 


Output
Value 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 (::). 


Output
Value of global x is 50
Value of local x is 10

Time Complexity: O(1)

Auxiliary Space: O(1)

Comment
Article Tags:
Article Tags: