Scope

Validity, Lifetime or Visibility of a variable.

 

Identifies where an object can be used.

 

2 types:

  • Global
  • Local

Any variable defined outside of any function in the program is considered global throughout the program.

 

Variables defined inside a function are considered locally scoped, and are valid within that function only. That is, the scope of their validity is only within the function in which they exist.

 

A locally scoped variable will override that of a global variable.

 

I have purposefully used the same name for the unique variable, to show its scoped validity.

 

Each function uses its own value for the same named variable, and thus do not use the global variable of the same name.

 

As soon as the function has executed, it’s data is lost and control is passed back to the main program with its set of variables.

 

Compiling & running the above would produce:

 

The value of the unique global variable is: 42
The value of the unique myFunction variable is: 5
The value of the unique myFunction variable is: 7
The value of the unique myFunction variable is: 12

Leave a Reply