Scope CS Thinking Example 2
Follow the full solution, then compare it with the other examples linked below.
Example 2
hardExplain why using global variables inside functions is generally discouraged.
Solution
- 1 Step 1: Global variables can be changed by any part of the program, making it hard to track their value.
- 2 Step 2: Functions that modify globals have side effects โ their behaviour depends on external state, making testing and debugging harder.
- 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
Example 1 medium
What is the output? SET x = 10. FUNCTION addFive(): SET x = 5. RETURN x + 5. OUTPUT addFive(). OUTPU
Example 3 mediumWhat is the output? SET y = 100. FUNCTION test(): OUTPUT y. test(). Will this work, or will there be
Example 4 mediumWhat is the output? Explain any errors. SET count = 0 FUNCTION increment() SET count = count + 1