Scope CS Thinking Example 4
Follow the full solution, then compare it with the other examples linked below.
Example 4
mediumWhat is the output? Explain any errors.
SET count = 0
FUNCTION increment()
SET count = count + 1
SET bonus = 10
END FUNCTION
increment()
OUTPUT count
OUTPUT bonus
Solution
- 1 Step 1: count is a global variable, set to 0.
- 2 Step 2: increment() runs. If the language allows modifying globals, count becomes 1. bonus is created as a local variable inside increment, set to 10.
- 3 Step 3: OUTPUT count โ outputs 1 (global was modified).
- 4 Step 4: OUTPUT bonus โ ERROR. bonus was local to increment() and does not exist outside it.
Answer
Output: 1, then an error on OUTPUT bonus. Local variables created inside a function are not accessible outside it โ they go out of scope when the function ends.
Scope rules protect functions from interfering with each other. A variable created inside a function is local by default and disappears when the function returns. Accessing it outside causes a 'not defined' error.
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 2 hardExplain why using global variables inside functions is generally discouraged.
Example 3 mediumWhat is the output? SET y = 100. FUNCTION test(): OUTPUT y. test(). Will this work, or will there be