Scope CS Thinking Example 1

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

Example 1

medium
What is the output? SET x = 10. FUNCTION addFive(): SET x = 5. RETURN x + 5. OUTPUT addFive(). OUTPUT x.

Solution

  1. 1
    Step 1: The function creates a local variable x = 5 (separate from the global x = 10).
  2. 2
    Step 2: addFive() returns 5 + 5 = 10. First output: 10.
  3. 3
    Step 3: The global x is still 10 (unchanged by the function). Second output: 10.

Answer

10, then 10. The function's local x does not affect the global x.
Scope determines where a variable can be accessed. Local variables inside a function are separate from global variables with the same name. This prevents functions from accidentally modifying external state.

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