levo

Problem Solving and Programming

Programming techniques: Global and local variables

  • 1 thing to know
  • Component 02
Start revising · £5/month

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.

Everything in your subscription

Runs, plus a mode for every other kind of session.

1Flash
2Imposter
3Fade
4Brain dump

Learn every subtopic in runs of four questions

Facts flash and fade, a wrong word hides in some of them, and a brain dump decides which questions are locked in.

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

Cram the night before, weakest topic first

A quick scan finds your weakest topics. Recall each fact you missed three times in a row.

If it matches, the search .
succeedsfailsrestarts

Blank Blitz consolidates the facts

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

✓What it iscovered
~Why it happenspartly there
How long it lastsnot there yet

Explain It tests your understanding

Explain a concept in your own words and see which of its points you covered.

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

Test It catches misconceptions

Spot the fault in a statement. The faults are the mistakes students make most often.

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.

Learn it in runs of four questions, each ending on a brain dump against the clock. Every question you lock in comes back the next day, then at longer gaps, each time just before you would forget it.

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