levo

Problem Solving and Programming

Programming techniques: Global and local variables

  • 1 thing to know
  • Component 02

Overview

Recall questions on the scope and lifetime of variables, local and global variables, predicting output when a local variable shadows a global one, why globals are discouraged and when they are justified, and fixing out-of-scope values.

What you need to know

Answer each one before you reveal it.

Your recallNot started
Key term

What is meant by the scope of a variable?

Questions from this subtopic

Each one with the model answer underneath.

  1. 1

    What is meant by the scope of a variable?

    Model answer

    The region of the program in which that variable can be seen and used. A local variable, declared inside a subroutine, is in scope only within that subroutine; code elsewhere using the same name is either an error or refers to a completely different variable. A global variable, declared in the main program and marked as global, is in scope throughout the program, including inside subroutines. Scope is decided by where the variable is declared, and it is what allows two subroutines to use the same name harmlessly.

  2. 2

    Scope and lifetime are not the same thing. Explain the difference.

    Model answer

    Scope is where in the program a variable can be used; lifetime is how long it exists in memory. A local variable is created when its subroutine is called and destroyed when that subroutine returns, so it forgets its value between calls and its memory is freed for reuse. A global variable is created once and lives until the program ends, holding memory the whole time. The two questions are separate: a variable can be alive but out of scope — a variable in the main program still exists while a subroutine is running, but the subroutine cannot see it and cannot use its name.

  3. 3

    What is printed here, and what would change if total were made global and set to 0 once in the main program instead? procedure count() total = 0 total = total + 1 print(total) endprocedure count() count() count()

    Model answer

    It prints 1, 1, 1. total is local to the procedure: it is created fresh on every call and set back to 0 each time, so it never remembers anything from the previous call, and it is destroyed when the procedure returns. If total were instead a global set to 0 once in the main program, with the line total = 0 removed from the procedure, the same three calls would print 1, 2, 3, because there is then a single variable that survives between calls and accumulates.

  4. 4

    The main program has a global variable x holding 10. A procedure then assigns 3 to a variable it calls x, which is local to it, and prints it; the main program prints x afterwards. What appears, and why is this a nasty source of bugs? global x = 10 procedure show() x = 3 print(x) endprocedure show() print(x)

    Model answer

    It prints 3 then 10. The assignment inside the procedure creates a local variable that happens to share the name x, and that local hides — shadows — the global for as long as the call lasts. The global is never touched, so the main program still sees 10. It is a nasty bug because a programmer who intended to update the global sees the change apparently take effect (the procedure prints 3) and then vanish, and because reading the code gives no visual clue that two different variables are involved.

  5. 5

    Why are global variables generally discouraged?

    Model answer

    Because any part of the program can change them. When one holds a wrong value you must search the whole program to find what wrote to it, so debugging and testing get much harder and a fault can appear a long way from its cause. They create hidden dependencies: a subroutine that reads a global is not self-contained, so it cannot simply be lifted into another program and reused. They invite accidental name clashes where two parts of a program reuse a name and quietly overwrite each other. They occupy memory for the whole run rather than only while needed. And they break encapsulation, so changing how a piece of data is stored can force changes in code everywhere.

  6. 6

    When is a global variable actually justified?

    Model answer

    When a value is genuinely needed across most of the program and must persist for the whole run: a constant such as a VAT rate or pi; a configuration setting such as a data file path or the chosen language; a single shared resource such as an open database connection; or state that many subroutines must read, such as whether a game is paused. Even then, passing the value in as a parameter, or declaring it as a read-only constant, is preferable where practical, because that makes the dependency visible in the subroutine's interface instead of hiding it.

Other ways to work this

The same content, four other ways.

What is inside Levo

Six ways to work the same material.

1Closed book
2Open book
3Closed book

The 3-step method, run for you

Answer cold, learn it, then prove it stuck. Levo tracks the jump between your first attempt and your last.

Processors: Structure, Performance and Types
Input, Output and Storage
Systems Software
Applications Generation

Cram a whole paper in one sitting

Sort every topic into what you know and what you do not, then drill only the weak ones.

If it matches, the search .
succeedsfailsrestarts

Blank Blitz makes facts automatic

Rapid timed gap-fills on the terms and numbers you need to recall without thinking.

A0 + 0 gives 0.
B0 + 1 gives 1.
C1 + 1 gives 0 carry 1.

Build It gets the exam shape right

Assemble a full-mark answer from its marking points, in the order an examiner wants them.

A global variable means a variable reachable from anywhere in the program.
TrueFalse

Test It catches misconceptions

Spot the fault in a statement. The traps are the mistakes students actually make.

721941163128510

Brain Breaks between sessions

Short focus games to reset attention, so the next set lands better than the last.

Every question in Problem Solving and Programming, on a schedule.

Attempt a question from memory, write the correct version, then attempt it again. Levo records the jump between your first attempt and your last, and brings each question back on the day you are due to forget it.

Or £46 a year, about £3.83 a month. Cancel anytime.