Scope can be defined as the accessibility of a variable.
Say for example, in every office, there is a restricted area where only a few people have access.
Similarly, in C++, the variables also have some access restrictions. The variables that are defined inside a Function, cannot be accessed outside of it.
#include <iostream> using namespace std; void myFunction() { int x = 5; } int main() { myFunction(); cout << x; return 0; }
So, in the first line itself, the Function myFunction() is called.
myFunction();
And the function execution begins.
void myFunction() { int x = 5; }
And initialised the variable x with 5 inside the function fun().
int x = 5;
Then we come to the print statement,
cout << x;
And end up with an error as output,
This is because the variable x is not accessable outside the Function. And that is called as Local Scope.
The variables that are declared inside a Function, can only be accessed inside the Function and is local to that Function. That is called the Local Scope of a variable.
Say for example, if there are two functions, firstFunction() and secondFunction().
#include <iostream> using namespace std; void firstFunction() { int x = 5; cout << "The variable x : " << x << " is not accesible outside the firstFunction()" << endl; } void secondFunction() { int y = 7; cout << "The variable y : " << y << " is not accesible outside the secondFunction()" << endl; } int main() { firstFunction(); secondFunction(); return 0; }
So, we have declared two functions, firstFunction(),
void firstFunction() { int x = 5; cout << "The variable x : "+x+" is not accesible outside the firstFunction()"; }
And secondFunction().
void secondFunction() { int y = 7; cout << "The variable y : "+y+" is not accesible outside the secondFunction()"; }
And we have two variables, x and y.
While x is declared inside the Function firstFunction() and is local to the firstFunction() and cannot be accessed outside it.
Similarly, y is declared inside the Function secondFunction() and is local to the secondFunction() and cannot be accessed outside it.
Next, let us see the Local Scope in nested Function.