3.9. Parameters and Variables are Local

Parameters and variables only exist inside their own functions. Within the confines of main, there is no such thing as phil. If you try to use it, the compiler will complain. Similarly, inside printTwice there is no such thing as argument.

The following code will show the output of the printTwice function. Notice that it is the argument ‘b’ that is outputted, not the variable ‘phil’.

Variables like this are said to be local. In order to keep track of parameters and local variables, it is useful to draw a stack diagram. Like state diagrams, stack diagrams show the value of each variable, but the variables are contained in larger boxes that indicate which function they belong to.

For example, the state diagram for printTwice looks like this:

image

Whenever a function is called, it creates a new instance of that function. Each instance of a function contains the parameters and local variables for that function. In the diagram an instance of a function is represented by a box with the name of the function on the outside and the variables and parameters inside.

In the example, main has one local variable, argument, and no parameters. printTwice has no local variables and one parameter, named phil.

You have attempted of activities on this page