Scope and Visibility

The scope says how long the variable lives or I can say how long the value in the variable is persisted without losing its value. For example look at the function below:

 

int somefunction()

{

            int x;

            int y;

            //Some work here

            x = 15;

            y = y * y * y;

}

 

In the above function the scope of the variable x and y is inside the function. That means when the function returns the variable values x and y are lost. You may not expect the value of 15 in x in the comment shown when the same function is called next time since the value is lost at the end of the previous function call.

 

OK. Visibility is the value x is visible only inside the function. Other functions are not aware of x. If you assume the value x is declared outside the function at the top of the CPP file and there are three more functions in the same .cpp file, then variable x is visible inside all the function.

 

In the above function Scope and visibility of variable x is inside somefunction()