Jump to content

Programming Fundamentals/Functions/Scope

From Wikiversity

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]
Main function
Main function
DisplayHello function
DisplayHello function

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:

  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

[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?

References

[edit | edit source]