The scope of a variable is the region of space where the value of that variable is valid.
The main reason for a scope is to keep variables with the same names confined to separate parts of a program. Programmers may use the same variable names repeatedly; therefore, the scope defines the region in which that variable is valid.
There are two types of scope:
They are both described in detail below.
Variables defined in the global scope can be accessed anywhere throughout the program. They are available to all the functions across the program.
Remember: global variables are available from the point they are defined until the end of the scope. This is a major reason why most global variables are declared at the start, to ensure their availability across the program.
#include <iostream>using namespace std;string name = "Alex"; // declare a global variableint main() {name= "Bob"; // update the value of variable in functioncout << name << endl; //print variablereturn 0;}
Variables defined in the local scope are only available inside the functions, loops, or classes in which they are defined.
Remember: global variables can exist with the same name; however, the compiler will always consider the variables within the local scope first. This means that global variables will not be called if a similar local variable exists.
This is shown below.
#include <iostream>using namespace std;//declare a global variable xint x = 100;int main() {//declare a local variable xint x = 10;//update the value of xx += 10;//print value of xcout << x << endl;return 0;}
The above example suggests that if a global variable needs to be updated, it should be ensured that no local variable with the same name exists or that the scope resolution operator is used.