Local Function Variable Scoping

 < Day Day Up > 



testFunctionOne(), although complete, is a simple example. Most functions you write will be far more complex and will no doubt require arguments to be passed to it and a value of some sort returned. To master the art of writing meaningful functions you will need to get smart about variable scoping rules and how they apply to functions.

It is helpful to think of a function as a world unto itself. Variables can be declared and used within the body of a function. Any variables declared within the body of a function are referred to as local variables. Local variables exist for the life of the function, that is, when the function is called, any local variables required are set up and ready for use by the function. When the function returns, its stack frame collapses and with it go all the local variables. Therefore, local function variables, unless declared as being static, exist and retain their values only for as long as the function exits actively in memory.

In this section I will discuss how local variables can be declared and used within a function, how global or file scope variables can be masked or hidden by local variables, how to use scoping blocks within a function, how to declare and use static function variables, and how function parameters are used by a function.

Declaring Local Variables

Variables can be declared and used within the body of a function. Any variables declared within the function are considered local to that function and are referred to as local variables. Study example 9.4:

Listing 9.4: local function variables

start example
1 void testFunctionTwo(){ 2    int i = 2; 3    cout<<"Local i = "<<i<<endl; 4 }
end example

Line 2 declares and initializes a variable named i within the body of testFunctionTwo() and prints its value to the screen.

Hiding Global Variables with Local Variables

A local variable declared within a function will hide a global variable of the same name. Consider the following example:

Listing 9.5: masking global variables

start example
1 #include "testfunctiontwo.h"  2 #include <iostream>  3 using namespace std;  4  5 int i = 1;  6  7 void testFunctionTwo(){  8    int i = 2;  9    cout<<"Local  i = "<<i<<endl; 10    cout<<"Global i = "<<::i<<endl; 11 }
end example

The variable i declared at file scope on line 5 will be masked or hidden by the declaration of testFunctionTwo()’s local variable i declared on line 8. There are several lessons to be learned here. First, functions have access to any global variables declared within their translation unit unless hidden by a local variable of the same name. Second, if a local variable hides a global variable, the global variable can be accessed via the :: operator as shown on line 10.

Using Scoping Blocks in Functions

Scoping blocks can be used within the body of a function to redeclare variables of the same name. Variables introduced in this fashion are considered to be within an enclosed scope and hide variables of the same name in the enclosing scope. Study the following example:

Example 9.6: block scope

start example

click to expand

end example

You generally will not use scoping blocks for the express purpose of hiding outer block variables, but you will regularly experience their effect when you use iteration or looping statements. Consider the following code:

Example 9.7: scope of variables in looping statements

start example

click to expand

end example

The variable i declared in the for statement on line 13 hides the local variable with the same name declared on line 9. The global i variable can be accessed within the body of the for loop using the :: operator.

Static Function Variables

The local function variables you have seen so far are created and destroyed with each invocation of their associated function. If you want a local variable to retain its value between function calls you must declare the variable as being static using the static keyword.

A static local function variable will be initialized when the function is first called. Any change to the value of a static variable will be preserved for use by the next invocation of the function. Examine the code in example 9.8.

Listing 9.8: static function variables

start example
1  #include "testfunctiontwo.h"  2  #include <iostream>  3  using namespace std;  4  5  void testFunctionTwo(){  6     static int i = 0;  7           int j = 0;  8  9     cout<<"Local Static i = "<<i++<<endl; 10     cout<<"Local Auto   j = "<<j++<<endl; 11  }
end example

Figure 9-3 shows the results of invoking testFunctionTwo() five times.


Figure 9-3: Results of Calling testFunctionTwo() Five Times with Static Variable

On each invocation of the function both variables are incremented after they are printed to the screen as is shown on lines 9 and 10 of example 9.8. When testFunctionTwo() is called the first time, both variables are initialized to zero. On the second call to testFunctionTwo() and on each call thereafter, the local variable i is reinitialized to zero while the static variable j retains its incremented value from the prior function call.

Static function variables come in handy when you need to preserve function state between function calls. Although the value of the static variable is preserved between function calls, its scope is still local to the function in which it is declared.

Scope of Function Parameters

When a function has a parameter list, the parameter names have local scope within the function. Any attempt to redeclare a local variable within the function that has the same name as one of its parameters will result in a compiler error. Function parameters hide global variables with the same name. Examine the following code:

Example 9.9: masking function parameters

start example

click to expand

end example

In this example, the function testFunctionThree() is defined to take one integer argument. The parameter name used to access the value of the argument supplied to the function when it is called is i. The following example shows testFunctionThree() being called from a main() function with the argument 5:

Listing 9.10: function call with argument

start example
1  #include <iostream> 2  #include "testfunctionthree.h" 3  using namespace std;  4 5  int main(){ 6     testFunctionThree(5); 7     return 0; 8  }
end example

Figure 9-4 shows the result of running this program.

click to expand
Figure 9-4: Results of Calling testFunctionThree() with an Argument Value of 5

Quick Review

Variables declared inside the body of a function have local scope within that function. Local variables will hide global variables of the same name. Local variables exist for the life of the function and will be reinitialized each time the function is called. If you need a local variable to retain its value between function calls use the static keyword in its declaration. Function parameters have local scope within the function and mask global variables with the same name. To access global variables with the same name as local variables use the :: operator.



 < Day Day Up > 



C++ for Artists. The Art, Philosophy, and Science of Object-Oriented Programming
C++ For Artists: The Art, Philosophy, And Science Of Object-Oriented Programming
ISBN: 1932504028
EAN: 2147483647
Year: 2003
Pages: 340
Authors: Rick Miller

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