The c++ scope operator USES of global and local variables

  • 2020-04-02 02:23:40
  • OfStack

In general, if you have two variables with the same name, one global and the other local, then the local variable has a higher priority in its scope and it shields the global variable.

Scope operator


#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 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 output is the value of the local variable num.

Scope operators can be used to solve the problem of local and global variables


//If we want to use a global variable of the same name in the scope of a local variable, we can prefix it with "::", where "::num" represents the global variable, :: is 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 is:


local avar =25
global avar =10

From this example, we can see that the scope operator can be used to solve the problem of local variables and global variables with the same name, that is, within the scope of local variables, the global variables with the same name can be accessed by ::.


Related articles: