Scope CS Thinking Example 2

Follow the full solution, then compare it with the other examples linked below.

Example 2

hard
Explain why using global variables inside functions is generally discouraged.

Solution

  1. 1
    Step 1: Global variables can be changed by any part of the program, making it hard to track their value.
  2. 2
    Step 2: Functions that modify globals have side effects โ€” their behaviour depends on external state, making testing and debugging harder.
  3. 3
    Step 3: Better practice: pass values as parameters and return results, keeping functions self-contained.

Answer

Global variables make programs harder to debug and maintain. Functions should use parameters and return values instead.
Minimising global state is a key principle of clean code. Functions that rely only on their parameters are predictable, testable, and reusable.

About Scope

The region of a program where a variable is accessible. Variables defined inside a function have local scope and exist only within that function. Variables defined outside all functions have global scope and are accessible from anywhere in the program.

Learn more about Scope โ†’

More Scope Examples