Typically, if there are two variables with the same name, one is a global variable and the other is a local variable, then the local variable has a higher priority within its scope and it masks the global variable.
Scope operator
Copy Code code as follows:
#include <iostream>
using namespace Std;
int num=10;
int main ()
{int num;
num=25;
cout<< "num is" <<num<<endl;
return 0;
}
The output of the program is the NUM is 25. In the output statement of the main function, the variable num used is the local variable defined within the main function, so the result of the output is the value of the local variable num.
The scope operator can be used to solve the problem of duplicate names of local variables and global variables
Copy Code code as follows:
If we want to use a global variable of the same name in the scope of a local variable, you can precede the variable with a "::", at which point:: num represents the global variable: the scope operator.
#include <iostream>
using namespace Std;
int Avar; global variable definition
int main ()
{int Avar;//local variable definition
avar=25;
:: avar=10;
cout<< "Local Avar =" <<avar<<endl;
cout<< "Global Avar =" <<::avar<<endl;
return 0;
}
The result:
Copy Code code as follows:
Local Avar =25
Global Avar =10
This example shows that the scope operator can be used to solve the problem of the duplicate name of a local variable and a global variable, that is, within the scope of a local variable: access to a masked global variable with the same names.