Programming Fundamentals/Functions/Scope
Appearance
The scope of a variable is the region of a computer program where the variable identifier can be used to refer to that variable.[1] This activity introduces variable scope. This activity will help you understand how to use variable scope in a program.
Objectives
[edit | edit source]- 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
[edit | edit source]- Learners should already be familiar with functions and parameters.
- Review Wikipedia: 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.[2]
- Local scope restricts variable visibility to a given block of code (an expression, block, function, file, or module, depending on the programming language).[3]
- Global scope has no visibility restrictions, and is generally considered bad practice due to the possibility of name collisions.[4]
Introduction
[edit | edit source]Review the flowchart example on the right.
Questions
[edit | edit source]- How many
name
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
[edit | edit source]With a partner, perform the following:
- Using a visual programming language, create a program matching the flowchart on the right.
- Save the program.
- Test the program to verify that it works correctly.
- Trade places, so that both partners have an opportunity to "drive" the visual programming environment.
- Change the environment to display local variables and step through the program one shape at a time.
- Working together, answer the questions listed above.
Applications
[edit | edit source]- 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?