Variable Scope


In the beginning of this chapter, you were introduced to the concept of variables. You saw the various data types, how to declare a variable, and what proper names you could use for variables (as well as ones you could not). There is one more topic concerning variables. This had to be left until after the discussion about the structure of a C++ program, and you will see why shortly. The topic at hand concerns WHERE you declare a variable. This is called variable scope. Consider the following example.

int main() {   int j;   return 0; }

This variable is declared inside the main function. That means it is only usable within that function. If you create other functions, they will not be able to access the variable j. This is referred to as a local variable. A local variable is a variable that is declared within a function, or within any block of code. Now let’s look at another example.

int j; int main() {    j++;    return 0; }

Notice that j was NOT declared inside the main function. It was declared outside of any function. This means that it can be used throughout your code. A variable declared outside of any function can be used in any function, and is referred to as a global variable. This is referred to as variable scope. Scope defines the range within which a variable can be used. If the variable has local scope, then its range is restricted to the function in which it was declared. It is essential to pay attention to the scope of your variables. It is not uncommon for a beginner to declare a variable inside one function, and then forget that it is only usable within that function.




C++ Programming Fundamentals
C++ Programming Fundamentals (Cyberrookies)
ISBN: 1584502371
EAN: 2147483647
Year: 2005
Pages: 197
Authors: Chuck Easttom

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net