Scope CS Thinking Example 3

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

Example 3

medium
What is the output? SET y = 100. FUNCTION test(): OUTPUT y. test(). Will this work, or will there be an error?

Solution

  1. 1
    Step 1: Most languages allow functions to read global variables (though not modify them without special syntax).
  2. 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