Skip to topic
    ← Back to course topics

    Subroutines (procedures/functions) — AQA A-Level Computer Science

    A subroutine is a named, self-contained block of instructions designed to perform a specific task, divided into functions that return a value and procedures that do not. In AQA A-Level Computer Science, mastering subroutine execution—including call stack frames, variable scope, and parameter passing by value versus reference—is vital for modular programming.

    Subroutines (procedures/functions) explained

    A subroutine is a named block of code that can be used in several places without being written out again each time.

    Read the full explanation

    Its main uses are to avoid repetition, to break a large problem into smaller, manageable parts, and to make programs easier to read, test and maintain. For example, a routine that validates a user's age can be written once and then called whenever an age must be checked, so a correction to the validation rule only needs to be made in one place. Recognising these uses means being able to explain why a programmer would choose to write a subroutine rather than repeat the same instructions inline.

    Your focus

    1. Be familiar with subroutines and their uses.

    Which command word is this?

    Set out the technical reasons or mechanisms behind a process (e.g. explaining why passing by reference can alter the original argument, requiring reference to memory addresses).

    Subroutines (procedures/functions) exam tips

    Topic Overview

    Subroutines are self-contained blocks of code that execute a specific operation when called, forming the cornerstone of procedural programming and modular decomposition. In AQA A-Level Computer Science, the curriculum distinguishes between procedures (which execute tasks without returning a value) and functions (which compute and return a value). Developing software using subroutines allows complex systems to be decomposed into manageable, testable, and reusable components.

    Beyond high-level structural design, students must understand the low-level execution mechanisms of subroutines within the CPU and system architecture. This includes stack frame allocation on the call stack, parameter passing mechanisms (by value vs by reference), and variable scoping rules. These concepts link modular programming directly to memory management, recursion, and processor register operations.

    Key Concepts
    • →Distinction between Procedures and Functions: Functions evaluate to a value and return it to the caller expression, whereas procedures execute statements without returning a value.
    • →Parameter Passing Mechanisms: Passing by value creates a duplicate copy of data in memory, preventing external side effects; passing by reference passes the memory address, enabling direct mutation of the original argument.
    • →Variable Scope and Lifetime: Local variables exist only within the activation record on the stack during subroutine execution, whereas global variables remain accessible throughout the entire program lifecycle.
    • →Call Stack and Stack Frames: Each subroutine invocation pushes an activation record holding the return address, parameters, and local variables onto the call stack, which is popped upon subroutine termination.
    Marking Points
    • Identifies reuse of the same block of code as a primary use of subroutines.
    • Explains that subroutines allow a problem to be decomposed into smaller parts.
    • Recognises that a single correction in a subroutine applies everywhere it is called.
    • Links subroutines to improved readability and maintainability of a program.
    Examiner Tips
    • 💡Give a concrete example of reuse, such as validating input, when asked about uses.
    • 💡Name at least two distinct uses, such as reuse and decomposition, rather than repeating one idea.
    • 💡Be clear that a subroutine is called from several points so its benefit is shared.
    • 💡When answering questions on recursive subroutines, explicitly mention that each recursive invocation generates a brand new stack frame containing its own set of local variables and return address.
    • 💡If asked to write a function in Paper 1 pseudo-code or Python, ensure you include a clear return statement; omitting the return transforms the subroutine into a procedure and costs marks.
    • 💡Use accurate terminology when discussing memory: explicitly reference the 'call stack', 'activation record', and 'return address' rather than vague descriptions like 'the computer remembers where it was'.
    Common Mistakes
    • Treats a subroutine as only useful for speed; reuse, decomposition and maintainability are the key uses.
    • Assumes a subroutine must return a value; procedures do not, functions do, and both are subroutines.
    • Confuses reuse with duplication by copying the same code into several places instead of calling one subroutine.
    • Assuming functions cannot modify parameters: While functions are primarily intended to return a single value, passing arguments by reference into a function can still produce unintended side effects on external variables.
    • Confusing arguments with parameters: Parameters (formal parameters) are the variable identifiers declared in the subroutine header; arguments (actual parameters) are the specific values or references passed into the subroutine upon invocation.
    • Believing global variables are preferable for convenience: Relying on global variables introduces tight coupling, increases the risk of unexpected side effects, and hinders modular reusability and testing.
    Revision Plan
    1. 1Week 1 (Days 1-3): Review the core definitions of functions vs procedures, practice writing both in your chosen programming language, and ensure correct usage of return statements.
    2. 2Week 1 (Days 4-7): Master parameter passing by tracing manual code snippets involving both 'byVal' and 'byRef', recording the state of variables before, during, and after execution.
    3. 3Week 2 (Days 1-4): Study call stack mechanics, practice drawing stack frames for nested and recursive subroutine calls, noting return addresses and local variable scopes.
    4. 4Week 2 (Days 5-7): Complete past AQA exam questions covering algorithm tracing, scoping errors, and 6-mark comparative questions on modular programming.
    Exam Question Types
    • 📋Trace and Dry Run Tables: Stepping through code that passes variables by value and reference, requiring accurate tracking of variable values across scopes.
    • 📋Short Answer Technical Definitions: Distinguishing between functions and procedures, or defining scope, activation records, and call stack operations.
    • 📋Code Writing and Refactoring: Writing a subroutine from a given specification or converting repetitive code into a modular procedure/function.
    Command Word Expectations (AQA)
    Explain

    Set out the technical reasons or mechanisms behind a process (e.g. explaining why passing by reference can alter the original argument, requiring reference to memory addresses).

    Compare

    Identify both similarities and differences between two concepts (e.g. comparing local versus global scope, or passing by value versus passing by reference) with balanced coverage.

    State / Identify

    Provide a concise, direct technical fact without long explanations (e.g. stating the items contained within a stack frame).

    How Students Lose Marks (Examiner Pitfalls)
    Pitfall: Confusing the mechanics and side effects of passing parameters by value versus passing by reference.
    ❌ Weak Answer (Loses Marks):Passing by reference means the subroutine uses the variable, while passing by value uses numbers.
    Example improved answer:Passing by value creates a local copy of the argument data in memory, meaning any modifications made within the subroutine do not affect the original variable in the calling program. Passing by reference passes the memory address of the actual variable, meaning any modifications directly alter the original variable value in the calling routine.
    Examiner Tip: Always specify that passing by value operates on a separate copy, whereas passing by reference passes a pointer or address that alters the original memory location.
    Pitfall: Failing to state the definitive technical difference between a procedure and a function.
    ❌ Weak Answer (Loses Marks):A function is used in math calculations while a procedure just runs ordinary lines of code.
    Example improved answer:Both procedures and functions are reusable subroutines; however, a function always returns a value to the calling statement, whereas a procedure performs a task without returning a value.
    Examiner Tip: Keep your distinction razor-sharp: a function returns a value; a procedure does not return a value.
    Step-by-Step Worked Solutions

    Question: A program executes the following pseudo-code: procedure swap(byRef a, byVal b) temp = a a = b b = temp endprocedure x = 10 y = 20 swap(x, y) print(x, y) Determine the output displayed by the print statement and explain how parameter passing rules produced this result.

    1. 1.Step 1: Identify how each variable is passed into the subroutine. 'x' is passed by reference to formal parameter 'a', meaning 'a' references the memory address of 'x'. 'y' is passed by value to formal parameter 'b', meaning 'b' receives an independent copy of 'y' (20).
    2. 2.Step 2: Trace the assignment operations inside 'swap'. 'temp' becomes 10 (the value of 'a'). 'a' is assigned the value of 'b' (20). Because 'a' is passed by reference, variable 'x' in the caller is updated directly to 20.
    3. 3.Step 3: Trace the next line. 'b' is assigned 'temp' (10). Because 'b' is passed by value, this only alters the local copy 'b'. The original caller variable 'y' remains unchanged at 20.
    4. 4.Step 4: Evaluate the output upon subroutine exit. 'x' has been permanently mutated to 20, while 'y' remains 20.
    Final Answer: Output: 20, 20. Variable 'x' was passed by reference, so mutating parameter 'a' updated 'x' to 20. Variable 'y' was passed by value, so modifying local parameter 'b' had no effect on 'y'.

    Question: Describe the contents and role of a call stack frame (activation record) generated when a subroutine call is executed.

    1. 1.Step 1: Define what an activation record is: a dedicated block of memory allocated on the call stack each time a subroutine is invoked.
    2. 2.Step 2: State the primary control element: it stores the return address (the memory location of the instruction in the calling code to jump back to once the subroutine terminates).
    3. 3.Step 3: State the data elements: it contains memory allocated for parameters passed into the subroutine and local variables declared within the subroutine scope.
    4. 4.Step 4: State any state-preservation elements: it may store saved register values from the calling context to restore the processor state upon return.
    Final Answer: A stack frame stores the return address to resume the caller code, parameter values or addresses passed to the subroutine, locally scoped variables, and saved register states.
    Active Recall Memory Test
    What is the key functional difference between a procedure and a function?
    Key Fact: A function returns a value to the calling instruction, whereas a procedure executes without returning a value.
    What data is stored inside a call stack frame (activation record)?
    Key Fact: The return address, passed parameters, local variables, and saved register values.
    What happens to the original variable in the caller when a parameter passed 'by value' is modified inside the subroutine?
    Key Fact: The original variable remains completely unchanged because the subroutine only operates on an independent local copy.
    Why does excessive recursion cause a 'stack overflow' error?
    Key Fact: Each recursive call allocates a new stack frame without releasing previous ones, eventually exhausting the call stack memory limit.
    Frequently Asked Questions
    What is the difference between an argument and a parameter?
    A parameter is the variable identifier defined within the subroutine signature or declaration (for example, 'def calculate(radius)'). An argument is the actual value or data passed into the subroutine when it is called (for example, 'calculate(5)'). While used interchangeably in casual conversation, AQA mark schemes expect precision when referring to formal parameters versus actual arguments.
    Can a procedure return a value using pass by reference?
    A procedure cannot return a value via a 'return' statement by definition. However, if a procedure accepts a parameter passed by reference, it can modify the memory location of that argument, effectively transmitting changed data back to the calling routine as a side effect. While this updates data in the caller, it is technically a mutation rather than a returned value.
    Why is pass by value generally safer than pass by reference?
    Pass by value guarantees that the subroutine works with an isolated duplicate of the data. This encapsulation prevents accidental side effects where code inside a subroutine inadvertently corrupts or overwrites critical variables belonging to the calling routine. It makes code easier to test, debug, and maintain across large software teams.
    What is variable shadowing in subroutine scoping?
    Variable shadowing occurs when a local variable declared inside a subroutine shares the exact same identifier as a global variable. Inside that subroutine's scope, the local variable takes precedence, effectively hiding or 'shadowing' the global variable. Any changes made to that identifier inside the subroutine apply only to the local variable.
    Why do programming languages use the stack for subroutines rather than the heap?
    The stack operates on a Last-In, First-Out (LIFO) basis, which perfectly mirrors the nested nature of subroutine calls where the most recently called subroutine must finish and return first. Stack memory allocation and deallocation require simply moving a stack pointer, making it far faster than dynamic heap allocation, which requires searching for free memory blocks.