Whether local variables in C + + can have the same name as global variables

Source: Internet
Author: User

This is a scope issue. A declaration introduces a name to a scope, and the scope of a local variable (usually defined in a function) begins at the point where the declaration is made until the block at which it resides ends (a block is a piece of code enclosed by {}). The scope of a global variable (defined outside of all functions, classes, namespaces) begins at the point of the declaration until the end of the file where the declaration resides. Local variables with the same name as global variables can mask global variables, and if you want to use global variables within a block, you need to resolve the operators by scope:: Reference. See the following example:

1#include <iostream>2 using namespacestd;3 intx;//define a global variable x4 intMain ()5 {6     intx;//masking Global Variables x7cout<<"Global x Initial value ="<<:: x <<Endl;8cout<<"Local x Initial value ="<< x <<Endl;9x =5;//Assigning a value to a local variable xTen:: x =6;//Resolving operators by Scope:: Referencing global variable x and changing its value Onecout<<"After assignment Global x ="<<:: x <<Endl; Acout<<"After assignment Local x ="<< x <<Endl; -     return 0; -}

The above example outputs the result:

01123941265

As can be seen from the example above, static objects such as global variables, static local variables are automatically initialized to 0 of the appropriate type if not shown, while local objects (also called Automatic objects) and objects created in free storage (dynamic objects or heap objects) will not be initialized.

Whether local variables in C + + can have the same name as global variables

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.