Skip to topic
    ← Back to course topics

    Local variables in subroutines — AQA A-Level Computer Science

    Local variables are declared within a subroutine and possess local scope, meaning they can only be accessed and modified within that specific block of code. They are allocated on the call stack upon subroutine entry and deallocated upon exit, preventing side effects and supporting recursion.

    Local variables in subroutines explained

    A local variable is a variable declared inside a subroutine.

    Read the full explanation

    It exists only while that subroutine runs and is not accessible to the rest of the program. Because local variables are created when the subroutine is called and discarded when it finishes, the same name can be reused in different subroutines without conflict. The statement requires you to know that local variables are declared within the subroutine, that they exist only during its execution, and that they are separate from global variables even if they share a name. For example, if a function declares total = 0 and a global variable also named total exists, changing the local total leaves the global one unchanged. Understanding this scope boundary is essential for predicting the output of programs that call several subroutines.

    Your focus

    1. Know that subroutines may declare their own variables, called local variables, and that local variables:

    Local variables in subroutines exam tips

    Topic Overview

    Local variables are identifiers declared inside a subroutine, procedure, or function whose accessibility is strictly confined to that specific subroutine. In AQA A-Level Computer Science, understanding local variables is fundamental to modular programming, structured design, and procedural abstraction.

    By restricting variable scope and managing memory via activation records on the call stack, local variables eliminate unintentional side effects across subroutines. This architectural isolation facilitates software testing, code reuse, and enables recursive execution without data corruption.

    Key Concepts
    • →Local Scope: The identifier is only visible, accessible, and referenceable within the block or subroutine in which it is declared.
    • →Stack Frame Allocation: Local variables are allocated inside an activation record pushed onto the call stack upon subroutine invocation.
    • →Automatic Deallocation: Memory allocated to local variables is automatically reclaimed when the subroutine completes its execution and its stack frame is popped.
    • →Prevention of Side Effects: Changes made to a local variable do not unintentionally alter program state outside the executing subroutine.
    • →Recursive Independence: Every recursive invocation instantiates a distinct set of local variables within separate stack frames.
    Marking Points
    • States that a local variable is declared inside a subroutine
    • Explains that a local variable exists only while the subroutine runs
    • Recognises that a local variable is not accessible outside its subroutine
    • Explains that a local variable with the same name as a global does not change the global
    Examiner Tips
    • 💡Identify where each variable is declared before predicting output
    • 💡Remember that a local variable is discarded when the subroutine ends
    • 💡Trace calls in order, resetting local variables each time a subroutine starts
    • 💡When asked to compare local and global variables, structure your response around three core criteria: accessibility (scope), memory usage (stack allocation vs static allocation), and maintenance/debugging (avoidance of side effects).
    • 💡In trace table questions involving recursion, ensure you track separate instances of local variables across different call stack levels rather than overwriting a single column value.
    Common Mistakes
    • Assumes a variable declared inside a function keeps its value between calls; a local variable is recreated each time the subroutine runs
    • Tries to read a local variable from the main program; a local variable is only accessible inside its own subroutine
    • Believes assigning to a local variable with the same name as a global changes the global value; the local one shadows the global inside the subroutine
    • Thinking local variables retain their values between separate subroutine calls; in standard procedural code, local variables are reinitialised on every call unless declared as static in specific languages.
    • Believing local variables with identical identifiers in different subroutines will clash; each subroutine has an isolated namespace and memory address space on the stack.
    • Assuming passing a variable as an argument automatically makes it global; parameter passing creates local copies (by value) or local references (by reference) without granting global scope.
    Revision Plan
    1. 1Stage 1: Define scope, lifetime, and namespace isolation for local and global variables.
    2. 2Stage 2: Diagram call stack frames during nested and recursive subroutine calls to trace local variable allocation.
    3. 3Stage 3: Practice 4-mark and 6-mark compare/contrast exam questions on modular programming principles.
    4. 4Stage 4: Complete past paper trace tables containing recursive routines with local state variables.
    Exam Question Types
    • 📋Comparative short-answer questions contrasting local and global variables in terms of scope, lifetime, and side effects.
    • 📋Memory management questions requiring explanation of stack frame creation, parameter passing, and deallocation.
    • 📋Algorithm trace questions with recursive procedures requiring tracking of distinct local variables per recursive depth.
    Command Word Expectations (AQA)
    Explain

    Set out the reasons for or causes of something. Must go beyond descriptive facts by linking technical mechanisms (e.g. stack allocation) directly to resulting benefits (e.g. memory efficiency).

    Compare

    Identify both similarities and differences between two concepts (such as local vs global variables), explicitly contrasting corresponding points rather than describing each in isolation.

    How Students Lose Marks (Examiner Pitfalls)
    Pitfall: Vaguely stating that local variables are 'better for memory' without explaining the allocation and deallocation lifecycle on the call stack.
    ❌ Weak Answer (Loses Marks):Local variables use less memory because they disappear when the function finishes.
    Example improved answer:Local variables are allocated space within a subroutine's stack frame on the call stack at execution time. Once the subroutine terminates, the stack frame is popped, immediately freeing that memory for reuse, unlike global variables which persist throughout runtime.
    Examiner Tip: Always link discussions of local variable lifetimes directly to call stack frames and memory reclamation to secure full technical marks.
    Pitfall: Confusing variable scope (where an identifier is accessible) with variable lifetime (when memory remains allocated for that identifier).
    ❌ Weak Answer (Loses Marks):The lifetime of a local variable is just the function it is written in.
    Example improved answer:Scope refers to the region of program code where the variable is visible and accessible (limited to the subroutine). Lifetime refers to the duration of time that memory remains allocated to that variable, beginning when the subroutine is called and terminating when it returns.
    Examiner Tip: Use the terms 'visibility/accessibility' for scope and 'allocation/deallocation duration' for lifetime to demonstrate precise conceptual understanding.
    Step-by-Step Worked Solutions

    Question: Explain two advantages of using local variables rather than global variables when developing modular programs. [4 marks]

    1. 1.Step 1: Identify the first distinct advantage related to program integrity and side effects.
    2. 2.Step 2: Explain this advantage in the context of modularity (independent development and testing without unintended state modifications).
    3. 3.Step 3: Identify the second distinct advantage related to memory efficiency and resource management.
    4. 4.Step 4: Explain how memory is managed dynamically using stack frames, freeing memory when execution concludes.
    Final Answer: Firstly, local variables prevent accidental side effects and unintended modifications by other subroutines because their scope is restricted to the declaring subroutine, allowing independent testing and maintenance of modules. Secondly, local variables provide efficient memory utilisation because their memory is allocated on the call stack only while the subroutine executes and is deallocated immediately upon termination, whereas global variables retain memory for the entire program runtime.

    Question: A programmer implements a recursive factorial algorithm. Describe how local variables are handled in memory across successive recursive calls. [4 marks]

    1. 1.Step 1: Identify the memory structure used during subroutine calls (the call stack).
    2. 2.Step 2: Describe what is generated for each recursive invocation (a new stack frame / activation record).
    3. 3.Step 3: State how local variables are isolated within each frame.
    4. 4.Step 4: Explain what happens when base cases are hit and calls return (stack frames popped, memory freed).
    Final Answer: Each recursive call generates a distinct stack frame (activation record) pushed onto the call stack. Each stack frame maintains its own independent copy of the local variables and parameters specific to that invocation. As recursive base cases are satisfied and calls unwind, each stack frame is popped in LIFO order, releasing the local variables' memory back to the system.
    Active Recall Memory Test
    Where are local variables physically stored during subroutine execution?
    Key Fact: In the subroutine's activation record (stack frame) on the call stack.
    What is the technical difference between variable scope and variable lifetime?
    Key Fact: Scope is the region of code where the variable is visible/accessible; lifetime is the time period during execution that memory remains allocated to it.
    Why are local variables essential for enabling recursive subroutine calls?
    Key Fact: Each recursive call requires its own independent instance of variables, preserved in separate stack frames as the recursion deepens.
    What is an unwanted 'side effect' in procedural programming?
    Key Fact: When a subroutine unexpectedly alters state or data outside of its local environment, commonly caused by modifying global variables.
    Frequently Asked Questions
    What is the difference between a local variable and a global variable?
    A local variable is declared within a specific subroutine and is accessible only within that block, with memory allocated on the stack during execution. A global variable is declared outside any subroutine, is accessible throughout the entire program code, and remains allocated in memory for the complete duration of the program runtime.
    Can a subroutine access a global variable if a local variable has the same name?
    In most programming languages, a local variable shadows (overrides) a global variable with the same identifier within that subroutine's scope. The subroutine will reference its own local variable by default, unless explicit scope resolution operators or language keywords (such as Python's 'global') are used.
    Why do local variables make debugging and software testing easier?
    Because local variables are contained entirely within their subroutine, modules can be tested in isolation (unit testing) without dependencies on external program states. If an incorrect value arises, the source of the error is guaranteed to reside within that specific subroutine rather than being modified unpredictably by external routines.
    What happens to a local variable when a subroutine finishes running?
    When a subroutine finishes execution, its stack frame (activation record) is popped from the call stack. The memory space allocated for that subroutine's local variables is immediately released and marked as available for future operations, destroying the local variable instances.