Barbara Ericson, Allen B. Downey, Jason L. Wright (Editor)
Section3.9Parameters and Variables are Local
Parameters and variables only exist inside their own functions. In the code below, 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.
Listing3.9.1.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.
Two boxes. One labeled main that contains a variable named ’argument’ which is ’b’. The other labeled printTwice that contains a variable named ’phil’ which is ’b’.
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.