Scope CS Thinking Example 3
Follow the full solution, then compare it with the other examples linked below.
Example 3
mediumWhat is the output? SET y = 100. FUNCTION test(): OUTPUT y. test(). Will this work, or will there be an error?
Solution
- 1 Step 1: Most languages allow functions to read global variables (though not modify them without special syntax).
- 2 Step 2: The function reads y = 100. Output: 100. No error.
Answer
Output: 100. The function can read the global variable y.
Reading global variables from functions usually works, but writing to them requires explicit declaration (e.g., `global y` in Python). The distinction between reading and writing globals is language-specific.
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 4 mediumWhat is the output? Explain any errors. SET count = 0 FUNCTION increment() SET count = count + 1