Scope

The scope of a variable determines who can see and use the variable and for how long the variable will be available until it is destroyed.

Local scope

Function parameters and variables declared inside a function (local variables) have local scope. That is to say that they can only be seen inside the function that declares them. The local variables are destroyed when the function exits and can no longer be accessed after the function exits.

Local scope prevents naming collisions. It is possible to have two variables with the same name, as long as they are in different scopes!

Be aware that it is possible to have nested scopes where two variables can exist with the same name but in different scopes, one inside another.

What happens in the example above is that within the nested block is a new variable ‘x’ created and this variable has its scope set to the local block which is smaller than the function main. Inside the nested scope is the outer variable ‘x’ not accessible it is hidden from view (this is called name hiding), only the variable ‘x’ declared in the inner scope can be seen and modified.  Notice that it is generally bad practice to declare a new variable with the same name is a smaller scope. The code quickly gets much more confusing when you have to remember which variable with the name ‘x’ you are seeing.

In the same way is it possible to declare a local variable with the same name as a function parameter.

This is also a bad practice and should always be avoided since it makes the code so much more difficult to read.

 

Facebookgoogle_pluslinkedinmail