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
#include <stdio.h>
int x = 50;
int main()
{
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;
}
|
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 (::).
C++
#include <iostream>
using namespace std;
int x = 50;
int main()
{
int x = 10;
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
Time Complexity: O(1)
Auxiliary Space: O(1)
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
21 Jun, 2022
Like Article
Save Article