Programming Fundamentals/Functions/Scope

The scope of a variable is the region of a computer program where the variable identifier can be used to refer to that variable. This activity introduces variable scope. This activity will help you understand how to use variable scope in a program.

Objectives

 * Understand variable scope.
 * Understand the difference between local variable scope and global variable scope.
 * Understand how variable scope impacts variable usage in a program.
 * Single-step through a program to observe variable scope.

Prerequisites

 * Learners should already be familiar with functions and parameters.
 * Review Scope (computer science).
 * The scope of a variable is also known as its visibility, where in the program it can be seen and accessed from.
 * Local scope restricts variable visibility to a given block of code (an expression, block, function, file, or module, depending on the programming language).
 * Global scope has no visibility restrictions, and is generally considered bad practice due to the possibility of name collisions.

Introduction


Review the flowchart example on the right.

Questions

 * How many  variables and parameters are used in the program?
 * What happens when two different functions use the same variable identifier? Does the identifier refer to the same variable or different variables?
 * Does the program display "Alice" and "Alice", or "Alice" and "Bob", or "Bob" and "Alice", or "Bob" and "Bob"? Why?
 * Does this program use local scope or global scope for variables and parameters?
 * What would happen if the program used the other type of scope?

Activity
With a partner, perform the following:
 * 1) Using a visual programming language, create a program matching the flowchart on the right.
 * 2) Save the program.
 * 3) Test the program to verify that it works correctly.
 * 4) Trade places, so that both partners have an opportunity to "drive" the visual programming environment.
 * 5) Change the environment to display local variables and step through the program one shape at a time.
 * 6) Working together, answer the questions listed above.

Applications

 * Identify situations in which local variable scope is preferred in a program.
 * Identify situations in which global variable scope is necessary in a program.
 * Discuss your activity experience with your classmates. What surprised you? What have you learned that you can apply to your own school or work environment?