Skip to topic
    ← Back to course topics

    Global variables in a programming language — AQA A-Level Computer Science

    A global variable is declared outside any subroutine and has global scope, making it accessible throughout the entire program during its complete runtime. In AQA A-Level Computer Science, understanding global variables involves contrasting them with local variables and evaluating the memory and maintainability drawbacks of side effects.

    Global variables in a programming language explained

    A global variable is declared outside any subroutine, usually at the top level of a program, and can be read and changed from anywhere in that program.

    Read the full explanation

    A local variable is declared inside a subroutine and can be used only within it, existing for as long as the subroutine runs. The statement as supplied is incomplete: it ends at 'global', so the exact contrast the learner must make is not fully specified, and this note does not invent one. The secure skill is to compare the two on scope (where the variable can be used), lifetime (how long it exists), and the risk each carries. Global variables are accessible everywhere, so unintended changes from distant code can be hard to trace; local variables limit this risk. Learners should be able to justify choosing a local variable over a global one when the value is needed only inside one subroutine.

    Your focus

    1. Be able to contrast local variables with global

    Global variables in a programming language exam tips

    Topic Overview

    In AQA A-Level Computer Science, variable declaration, scope, and lifetime form the bedrock of procedural and modular programming paradigms. Global variables are declared in the main body of a program outside of any function or procedure, granting them program-wide accessibility and a lifetime that extends throughout execution.

    While global variables offer convenience by eliminating the need to pass data through multiple parameter lists, excessive reliance on them undermines modularity and software reliability. Mastering this topic requires an understanding of how data is represented in memory and how local variable encapsulation protects programs against inadvertent side effects.

    Key Concepts
    • →Scope vs. Lifetime: Scope defines the code blocks where an identifier is visible and directly accessible; lifetime defines the duration between allocation and deallocation in memory.
    • →Global Namespace and Visibility: Global variables exist outside subroutines, meaning any subroutine can read or overwrite their value unless shadowed by an identical local identifier.
    • →Side Effects and Testing: When subroutines modify global variables, they produce hidden dependencies (side effects) that prevent modularity and prevent isolated unit testing.
    • →Memory Implications: Global variables occupy memory persistently in static data segments, whereas local variables use the call stack and are freed upon subroutine exit.
    Marking Points
    • Identifies that a global variable is declared outside subroutines and is accessible throughout the program
    • Identifies that a local variable is declared inside a subroutine and is accessible only within it
    • Compares lifetime, noting a local variable exists only while its subroutine runs
    • Explains that global variables risk unintended changes from any part of the program
    Examiner Tips
    • 💡Structure a contrast around scope, lifetime and risk so each point is clearly comparative
    • 💡Use the location of the declaration as evidence for the scope you state
    • 💡Give a concrete reason for preferring a local variable rather than only describing both
    • 💡When asked why global variables make debugging hard, explicitly mention 'unintended side effects' where one subroutine alters a value that another subroutine relies upon.
    • 💡Link discussions of local variables back to the call stack and stack frames to gain high marks in architecture and systems architecture cross-over questions.
    Common Mistakes
    • States that global variables cannot be changed; correct it by noting any subroutine can read and modify them
    • Assumes local and global variables share the same scope; correct it by distinguishing where each can be used
    • Ignores lifetime when contrasting the two; correct it by stating when each variable exists
    • Thinking local and global variables cannot share the same identifier: Most languages allow a local variable to have the same name as a global variable, which results in the local variable 'shadowing' or overriding the global variable within that subroutine's local scope.
    • Assuming passing by reference duplicates data like a global variable: Passing by reference passes only a pointer/memory address on the call stack; it does not replicate the full dataset, yet it maintains clear parameter contracts unlike undeclared global variable usage.
    Revision Plan
    1. 1Day 1-2: Write small procedural code samples in your chosen language showing variable shadowing and global keyword mechanics.
    2. 2Day 3-4: Draw call stack diagrams contrasting how static memory for global variables persists while stack frames for local variables are pushed and popped.
    3. 3Day 5: Practice 4-mark and 6-mark past exam questions focusing on code modularity, maintainability, and parameter passing.
    4. 4Day 6-7: Complete active recall quizzes distinguishing scope, lifetime, side effects, and re-entrancy.
    Exam Question Types
    • 📋Comparative Explain Questions: E.g., 'Explain two differences between local and global variables' (Focus on scope, lifetime, and memory allocation).
    • 📋Code Trace/Dry Run: Stepping through code snippets where a global variable is modified inside loops and subroutines to determine final output.
    • 📋Software Engineering Evaluation: Discussing whether a software scenario should refactor global data into passed parameters to facilitate teamwork and modular testing.
    Command Word Expectations (AQA)
    Explain

    Requires a linked justification identifying a feature and detailing its programming consequence (e.g., 'Global variables have global scope, meaning any subroutine can alter their value, which can cause unexpected side effects during runtime').

    Compare

    Identify both similarities and differences between two concepts (such as local vs global variables) across direct criteria such as scope, lifetime, and stack usage.

    How Students Lose Marks (Examiner Pitfalls)
    Pitfall: Confusing the concepts of variable 'scope' with variable 'lifetime'.
    ❌ Weak Answer (Loses Marks):A global variable lives everywhere, but a local variable is deleted when the program moves away.
    Example improved answer:Scope refers to the visibility or region of the program code where a variable can be accessed. Lifetime refers to the duration of program execution during which the variable retains allocated memory. A global variable has global scope (accessible by any subroutine) and a lifetime spanning the entire execution of the program.
    Examiner Tip: Always explicitly define scope as visibility/accessibility across program modules and lifetime as persistence in memory during execution.
    Pitfall: Vaguely stating that global variables are 'bad' without explaining the software engineering consequences.
    ❌ Weak Answer (Loses Marks):Programmers should not use global variables because they make code messy and are bad practice.
    Example improved answer:Excessive use of global variables compromises modularity. Multiple subroutines can unexpectedly mutate the variable's state, leading to side effects that make debugging and unit testing exceptionally difficult. Furthermore, global variables permanently occupy memory for the entire program execution rather than being reclaimed on subroutine termination.
    Examiner Tip: Use technical terms like 'unintended side effects', 'loss of independent modularity', and 'stack frame deallocation' when comparing with local variables.
    Step-by-Step Worked Solutions

    Question: A student writes a program where an array of 50,000 records is stored as a global variable. Another student suggests that passing the array as a local parameter by reference to subroutines would be better practice. Explain one advantage and one disadvantage of keeping the array as a global variable rather than passing it as a local parameter by reference.

    1. 1.Step 1: Identify how global variables function in terms of memory and parameter passing overhead. A global variable does not require memory overhead on the call stack for passing references or parameter bindings.
    2. 2.Step 2: Evaluate the disadvantage relating to program architecture and side effects. Any subroutine in the program can modify the array without clear dependency documentation.
    3. 3.Step 3: Structure the comparison addressing both advantage and disadvantage using exact AQA terminology.
    Final Answer: Advantage: Subroutines can access the array directly without the overhead of passing parameter addresses onto the call stack, simplifying subroutine interfaces. Disadvantage: It introduces side effects, as any part of the program can inadvertently alter the array data, making independent debugging and testing of subroutines difficult.

    Question: Describe how variable memory allocation differs between a global integer variable and a local integer variable declared within a recursive function.

    1. 1.Step 1: State the memory segment and lifetime associated with a global integer variable.
    2. 2.Step 2: State the memory segment and allocation mechanism for a local integer variable within a recursive call.
    3. 3.Step 3: Contrast their behavior across repeated/nested subroutine calls.
    Final Answer: A global integer is allocated in static/data memory when the program starts and retains a single fixed memory location until termination. In contrast, each recursive call allocates a new instance of the local integer on the call stack within a distinct stack frame; this memory is automatically deallocated as soon as that specific subroutine invocation returns.
    Active Recall Memory Test
    What is the scope of a global variable?
    Key Fact: The entire program (accessible from all modules and subroutines).
    What is meant by a 'side effect' in relation to global variables?
    Key Fact: When a subroutine unexpectedly modifies a global variable, altering the state of the program outside its local environment.
    Where in memory are local variables stored compared to global variables?
    Key Fact: Local variables are stored in stack frames on the call stack; global variables are stored in static/global data segments.
    What is 'shadowing' in programming languages?
    Key Fact: When a local variable is declared with the same name as a global variable, temporarily hiding the global variable within that local scope.
    Frequently Asked Questions
    Why are global variables considered bad practice in AQA Computer Science?
    Global variables are discouraged because they introduce hidden dependencies between modules, creating unintended side effects where changes in one subroutine break another. This violates the principle of encapsulation, making automated unit testing, debugging, and code reuse across different projects far more difficult.
    What is the difference between scope and lifetime?
    Scope is a spatial property defining the specific regions or blocks of code where an identifier can be referenced by the compiler or interpreter. Lifetime is a temporal property defining the period of time during program execution when memory remains allocated to that variable.
    Can a local variable have the same name as a global variable?
    Yes, in most programming languages this is allowed and is known as variable shadowing. When this occurs, the local variable takes precedence within its containing subroutine, masking the global variable unless explicit scope resolution operators are used.
    Are global constants considered as problematic as global variables?
    No, global constants are widely accepted in software engineering. Because their values are immutable (cannot be reassigned after declaration), they provide safe, universal access to configuration settings or mathematical constants without any risk of unintended side effects.