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