Understanding Variable scope is very important because it can sometime leads us to unwanted value changing or hazards while coding. Like, we have declared a variable but still its showing error while compiling or running. Look at the following code,
for(int x=0;x<5;x++) //For Loop 01
cout<<"Inside For Loop 01";
cout<<x<<" times"; //Line01
When we will compile this code we get some kind of error msg which may vary from compiler to compiler, but in general the error msg will be related to the variable x.
The area or portion of code within which we can use a variable and beyond which we can't is the scope of the variable.
In the above given example code, we declared the variable 'x' in the parenthesis of the for loop. Thus the variable x will only be allowed to use inside the for loop. Thus when we used x at Line01 the compiler produces error.
In the very same way, a variable declared within a function can only be used inside the function, not from the outer world.
We have to remember another thing that the permission of using variables is high at the bottom and low at the top. Look at the following code,
for(int x=0;x<2;x++) //For Loop 01
for(int y=0;y<2;y++) //For Loop 02
cout<<"x = "<<x<<" ; y = "<<y<<" From For Loop 02\n";
cout<<"Back into For Loop 01\n\n";}
Now, in the above code, we placed another for loop called 'For Loop 02' inside the 'For Loop 01'. We declared variable 'x' in 'For Loop 01' and 'y' in 'For Loop 02'.
Here, though the 'For Loop 01' contains the 'For Loop 02', it can not access the variable 'y' declared with 'For Loop 02'. But though 'For Loop 02' is working under the 'For Loop 01', it can access the variable 'x' declared with 'For Loop 01' just because both 'For Loop 02' and the variable 'x' are inside 'For Loop 01'.
int x = 5;
}cout<<"X = "<<x;
Again, the above code will also produce error as 'x' has been declared inside braces of 'if....else' and it has been used outside the boundary of 'if...else'.
So the bottom line, in general, is that a variable declared within a pair of braces can only be used inside that pari of braces.
Remember, OOP enables polymorphism, inheritence etc learning which you may get confused with the above given concept, where you may find a class object is using a variable of another class. But actually, its still ok. I will discuss those very soon.