Section 18.4 The Scope of a Variable
With the introduction of functions to our programs, we need to understand the area in which variable names are meaningful.
The scope of a variable refers to those parts of your code in which it has meaning and therefore can be used. For example, a variable declared inside a function can only be used inside that function and is not known elsewhere in your code. Try it out!
Activity 18.1.
In the following code window, we explore what happens if two functions use the same names for their variables. What do you expect will be the values of a and b in each of the functions?
admin.....open in new window
After running the code, did the values in each function surprise you? How did they compare to what you initially expected?
Subsection 18.4.1 It Gets Worse...
Activity 18.2.
Now, what happens if we start mixing up variable names between functions? Everything should be fine, right?
What do you think the below code will print? It is really important and beneficial for your learning to think about this first and to try to run through the code in your head. That’s why there is no Run
button!
admin.....open in new window
Subsection 18.4.2 Okay... Here is the Run
button...
If you have really thought this through, now hit the Run
button and compare. Is this what you expected? Why or why not? Be sure to ask questions!
admin.....open in new window