CIE IGCSE | 8.1.6C Local and Global Variables

Lesson objective

Explain variable scope, identify local and global declarations, trace shared changes and local calculations, and choose suitable ways to pass results between routines.

Learn

8.1.6C | LOCAL AND GLOBAL VARIABLES

01 | A NAME HAS A REACH

Imagine a quiz program with a main score and a function calculating bonus points. The function needs a temporary value for its calculation. Should every other part of the quiz be able to use that temporary name?

Scope is the region of a program where a declared name can be used to refer to its variable. It answers “Where can these instructions access this variable?” rather than “What value does it hold?”

A local variable is declared within a routine and used within that routine. A global variable is declared at program level, outside the routines, and is available across the program. In these examples, routines means procedures and functions.

02 | A LOCAL VARIABLE BELONGS TO ITS ROUTINE

Double uses a local variable called Result. Its declaration is inside the function body, between FUNCTION and ENDFUNCTION. Instructions in Double can assign and read Result.

When the main program calls Double(6), Result becomes twelve inside the function. RETURN sends that value to the caller. The caller’s Answer receives twelve, but the caller cannot use Double’s local name Result directly.

The value can be communicated; the local name’s scope has not expanded. Returning a result is not the same as making a local variable global.

FUNCTION Double(Number : INTEGER) RETURNS INTEGER
  DECLARE Result : INTEGER
  Result ← Number * 2
  RETURN Result
ENDFUNCTION

DECLARE Answer : INTEGER
Answer ← Double(6)
OUTPUT Answer

03 | LOOK AT THE DECLARATION, NOT JUST THE NAME

Result sounds generic, but that does not make it global. The declaration’s location determines its role in this example. A meaningful name helps readers; it does not change scope.

If another function declares its own local Result, the two declarations refer to separate working variables. They can hold different values without one routine overwriting the other’s local value.

Likewise, a routine’s local Score is not automatically the main program’s Score just because the spelling matches. Before tracing an assignment, identify which declaration the name refers to.

04 | VISUALISE LOCAL AND GLOBAL SCOPE

The outer box represents program-level state. The inner boxes show the working names available inside particular routines. A local name in one routine is not available to a sibling routine or directly to the main program.

PROGRAM LEVEL | GLOBAL Score

Main instructions and both routines can access the global Score in this example.

AwardPoints

Local parameter: Points

Local variable: NewScore

Can also access global Score.

ShowScore

Can access global Score.

Cannot directly use AwardPoints’ local NewScore or parameter Points.

“Global” describes availability within the program. It does not mean the variable is visible on the internet, shared between all users or permanently stored in a database.

05 | A GLOBAL VARIABLE IS SHARED PROGRAM STATE

The quiz’s Score is declared outside the procedures, so it is global in this example. Both AwardPoints and ShowScore refer to that same variable. Shared state means several parts of the program can access the same stored information.

The main program initialises Score to zero before calling either routine. AwardPoints adds five to the shared Score. ShowScore then outputs five because it reads the updated value.

Declaration and initialisation are still different: DECLARE Score : INTEGER does not guarantee an initial value of zero. The assignment supplies that starting value.

DECLARE Score : INTEGER

PROCEDURE AwardPoints
  Score ← Score + 5
ENDPROCEDURE

PROCEDURE ShowScore
  OUTPUT Score
ENDPROCEDURE

Score ← 0
CALL AwardPoints
CALL ShowScore

06 | TRACE CHANGES TO THE SAME GLOBAL VARIABLE

Each call to AwardPoints reads the current global value before replacing it with a new one. Starting from zero, two calls produce five and then ten.

The second call does not begin with a new Score of zero. Score is the shared variable initialised by the main program, and nothing in AwardPoints resets it.

Scope tells us that both routines can access Score; the trace tells us what its current value is at each moment.

One global variable retains changes across these calls
Instruction completedGlobal ScoreReason
Score ← 00Main program initialises it
First CALL AwardPoints5Procedure adds five
Second CALL AwardPoints10Procedure adds five to the current five
CALL ShowScore10OUTPUT reads without changing it

07 | PARAMETERS ARE LOCAL NAMES FOR SUPPLIED VALUES

A parameter name belongs to its routine. In AddBonus, Base and Bonus receive values supplied by the caller. They are available within that function, not as new global names for the main program to use.

At AddBonus(Score, 5), the caller supplies the current score and five. Total is a local working variable. RETURN sends the result out, then the caller explicitly assigns it to Score.

These examples do not assign to parameters or use a special reference-passing mechanism. Do not assume that giving a routine an argument automatically changes the caller’s variable.

FUNCTION AddBonus(Base : INTEGER, Bonus : INTEGER) RETURNS INTEGER
  DECLARE Total : INTEGER
  Total ← Base + Bonus
  RETURN Total
ENDFUNCTION

DECLARE Score : INTEGER
Score ← 10
Score ← AddBonus(Score, 5)
OUTPUT Score

08 | SENDING A VALUE OUT DOES NOT EXPOSE ITS NAME

AddBonus returns fifteen, so Score becomes fifteen in the caller. The main program cannot then output Total as though that local declaration belonged to it.

For a procedure, values can be displayed inside its body without exposing its local names. For a function, RETURN provides a clear route for one result to leave the routine.

In either case, distinguish the value from the identifier used to hold it during the calculation. Two variables can hold equal values and still be separate variables with different scopes.

09 | INITIALISE LOCAL WORK FOR EACH CALL

A local variable does not mean “automatically starts at zero”. If a calculation needs a starting value, initialise it explicitly inside the routine.

SumTo sets Total to zero every time it is called. SumTo(3) therefore returns six, and a later SumTo(2) returns three. The second call’s total does not include the first call’s six.

In this ordinary routine model, local working values belong to the current call. Scope and lifetime are related but different: scope concerns where a name can be accessed; lifetime concerns how long its variable exists. These examples use temporary local working values and no retained local state.

FUNCTION SumTo(Limit : INTEGER) RETURNS INTEGER
  DECLARE Counter : INTEGER
  DECLARE Total : INTEGER
  Total ← 0
  FOR Counter ← 1 TO Limit
    Total ← Total + Counter
  NEXT Counter
  RETURN Total
ENDFUNCTION

OUTPUT SumTo(3)
OUTPUT SumTo(2)

10 | STEP THROUGH LOCAL WORK AND A GLOBAL UPDATE

AwardPoints below has a local parameter Points and a local variable NewScore. It reads global Score, calculates a local new value, then explicitly updates global Score. Predict which value is shared and which names are confined to the procedure.

DECLARE Score : INTEGER

PROCEDURE AwardPoints(Points : INTEGER)
  DECLARE NewScore : INTEGER
  NewScore ← Score + Points
  Score ← NewScore
ENDPROCEDURE

Score ← 10
CALL AwardPoints(5)
OUTPUT Score

11 | TRY THE SCOPE TRACE

Choose a starting global score and points to award. The trace separates global Score from local Points and NewScore. After the procedure finishes, the caller reads the changed Score.

    The demo uses separate names to make the access clear. A real program’s variables should be traced against their declarations in the same way.

    12 | SAME NAME DOES NOT ALWAYS MEAN SAME VARIABLE

    Two different functions can each declare a local Total. One calculates ticket cost; the other calculates a reading sum. Those local declarations are separate, so calling the second does not change the first’s local Total.

    Some languages also allow a local declaration with the same name as a global declaration. The local name then shadows the global name in that local scope: the same spelling refers to a different variable there.

    Exact scope rules vary between programming languages. For clear Cambridge pseudocode answers, avoid local and global names that collide. Use distinct names and explicit parameters or returned values so the intended variable is unambiguous.

    13 | WHY LOCAL VARIABLES USUALLY HELP

    Local working variables limit unnecessary access. Another routine cannot accidentally assign to a helper’s local Total through that local name. This makes it easier to reason about which instructions can change a value.

    Parameters show what information a routine needs, and a returned value shows what it produces. This helps test the routine with different inputs and reduces reliance on hidden global state.

    Local scope is a program-organisation feature, not a password or data-security barrier. It helps prevent unintended interactions within code; it does not encrypt personal data or protect a database by itself.

    14 | WHEN GLOBAL STATE HELPS, AND WHAT IT COSTS

    A global variable can make sense for state deliberately shared across several routines, such as the current score or a program-wide setting. The routines then need a clear agreement about who initialises it and who may change it.

    Its wider availability also creates risks. A helper might change the score unexpectedly, or a routine may depend on a particular earlier call having run. The routine’s parameter list alone no longer reveals all its dependencies.

    Consider an explicit alternative: a function receives the current score and points, returns the new score, and the caller assigns the result. This makes the update visible at the call site. Global variables are not always wrong, but unnecessary shared state makes testing and debugging harder.

    15 | CHECK SCOPE BEFORE CHECKING THE VALUE

    First locate each declaration: is it outside routines, inside a routine, or a parameter in its header? Then identify which instructions can use that name. Only after that should you trace its assigned values.

    A useful explanation is: “NewScore is local because it is declared inside AwardPoints. The main program cannot use that local name. Score is global, therefore the procedure’s assignment updates the same variable the main program later outputs.”

    Avoid treating a returned value as a globally available variable, assuming every local starts at zero, or relying on an uninitialised global. The next lesson introduces library routines you can call without writing their definitions yourself.

    MATCH THE VARIABLE USE TO ITS ROLE

    Terminology

    Terminology

    Scope

    The region of a program where a declared name can refer to its variable.

    Local variable

    A variable declared within a routine and available within that routine.

    Global variable

    A variable declared at program level, outside routines, and available across the program.

    Declaration

    An instruction introducing a variable and its data type.

    Initialisation

    Giving a variable a starting value before it is used.

    Routine

    A named task implemented as a procedure or function.

    Parameter

    A local routine name receiving a supplied value at a call.

    Argument

    A value or expression supplied to a routine by its caller.

    Caller

    The part of the program making a routine call.

    Shared state

    Information stored in variables accessed by multiple parts of a program.

    Global update

    An assignment changing a shared program-level variable.

    Local working value

    Temporary information used within a routine’s calculation.

    Return value

    A function result sent to its calling expression.

    Explicit data flow

    Supplying values and receiving results through visible parameters and assignments.

    Dependency

    Information or state a routine needs in order to perform its task.

    Shadowing

    A local declaration using the same name as an outer declaration and hiding that name within the local scope in languages that permit it.

    Lifetime

    How long a variable exists, distinct from where its name can be used.

    Trace

    A step-by-step record of relevant variables and executed instructions.

    Questions

    Questions

    CHECK YOUR UNDERSTANDING

    Select all correct choices. Each exact set earns one point.

    1. Which describe local variables?
    2. Which describe global Score in the shared-score example?
    3. Score starts at zero; AwardPoints adds five and is called twice. What happens?
    4. Double declares local Result and returns twelve into caller Answer. Which apply?
    5. Which statements about parameters are correct here?
    6. SumTo initialises local Total to zero on each call. What do SumTo(3) and SumTo(2) return?
    7. Which are risks of unnecessary global variables?
    8. Which distinctions are correct?

    EXPLAIN AND COMPARE

    Write your answers before revealing each sample.

    1. Define scope and distinguish local from global variables.

    2. Explain why returning local Result does not make Result global.

    3. Trace global Score starting at zero through two calls that each add five.

    4. Explain the roles of Points, NewScore and Score in AwardPoints.

    5. Explain why initialisation is still needed for a local running total.

    6. Compare scope with lifetime.

    7. Explain two benefits of parameters and a returned result instead of hidden global dependencies.

    8. Suggest a situation for a global variable and explain a risk.

    BUILD IT | REMOVE A HIDDEN DEPENDENCY

    A bonus routine currently reads and updates global Score. Rewrite the calculation as a function NewScore with INTEGER parameters CurrentScore and Bonus. Declare local UpdatedScore, return its calculated value, and explicitly assign the result to Score in the main program. Start with ten and award five, then two. Identify every declaration’s scope.

    Reveal one possible solution
    FUNCTION NewScore(CurrentScore : INTEGER, Bonus : INTEGER) RETURNS INTEGER
      DECLARE UpdatedScore : INTEGER
      UpdatedScore ← CurrentScore + Bonus
      RETURN UpdatedScore
    ENDFUNCTION
    
    DECLARE Score : INTEGER
    Score ← 10
    Score ← NewScore(Score, 5)
    Score ← NewScore(Score, 2)
    OUTPUT Score

    Score becomes fifteen, then seventeen. Its declaration is at program level. CurrentScore and Bonus are parameter names local to NewScore; UpdatedScore is declared locally in its body. The function does not directly name or update global Score. The caller explicitly assigns each returned result, making the update visible.

    Flashcards

    Flashcards

    Click to flip. Select the ideas you need to revisit.

    0 cards selected for revision.

      Selections are kept while this page is open.

      Workbook

      Workbook

      COMING SOON

      The workbook for 8.1.6C Local and Global Variables is coming soon. Complete the matching task and written questions in your exercise book.