C + + scope operator usage (global variables and local variables) _c language

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.