With a qualified name. Consider:
int x = 111;
int main() {
int x = 222;
std::cout << x << ' ' << ::x << std::endl;
}
Prints 222 111
. Demo
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Hi,
I am new learner of C++. Having questions with Global vairable and Local vairable.
When there are a Global variable and Local variable with the same name, how will you access the global variable?
Many Many Thanks
With a qualified name. Consider:
int x = 111;
int main() {
int x = 222;
std::cout << x << ' ' << ::x << std::endl;
}
Prints 222 111
. Demo
The example posted by Igor uses the scope resolution operator:
Scope resolution operator: ::
https://learn.microsoft.com/en-us/cpp/cpp/scope-resolution-operator?view=msvc-170
"A scope resolution operator without a scope qualifier
refers to the global namespace."
(Thanks for converting to Answer. I was/am just wanting to add comments to King's typing)
In C++ programming variable naming styles, local variable naming is casual, global variable naming is more descriptive and having "g_" prefix, they are not to necessarily have a same name. For example,
#include <iostream>
int g_totalAmount = 0;
void IncreaseAmount(int amount)
{
g_totalAmount += amount;
}
int main()
{
IncreaseAmount(100);
IncreaseAmount(200);
std::cout << g_totalAmount << std::endl;
return 0;
}
// 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;
}