Understand and use local and global variables

Programming – Understanding and Using Local and Global Variables (Cambridge IGCSE Computer Science 0478)

1. Variables, Constants and Identifiers

  • Variable: a named storage location that holds a value which may change while the program runs.
  • Constant: a named value that never changes after it has been defined.
  • Identifier (name): the label you give to a variable, constant, routine, array, etc.

1.1. Naming rules (syllabus)

  • May contain letters (A‑Z), digits (0‑9) and the underscore “_”.
  • Must start with a letter.
  • Case‑insensitive – Score and score refer to the same identifier.
  • Cannot be a reserved word (e.g. IF, FOR, TRUE, PROCEDURE).
  • Good practice: use meaningful, descriptive names (e.g. totalScore, maxAttempts).

1.2. Declaration syntax (exam pseudocode)

StatementPurpose
DECLARE identifier : typeCreates a variable of the given type.
CONSTANT identifiervalueCreates a constant with the specified value.

1.3. Basic data types

TypeTypical valuesLiteral syntax
INTEGERWhole numbers5, -12, 0
REALNumbers with a decimal point3.14, -0.5, 2.0
CHARSingle character'A', '9', '#'
STRINGSequence of characters"Hello", "IGCSE"
BOOLEANTrue / False valuesTRUE, FALSE

1.4. Operators (allowed in the syllabus)

CategoryOperatorsExample
Arithmetic+ – * / ^ DIV MOD5 + 3, 10 DIV 3
Relational= < <= > >= <>score >= 50
Logical (Boolean)AND OR NOTpassed AND attended

2. Scope – Where a Variable Can Be Used

  • Global scope: declared outside any routine; visible to every routine in the program.
  • Local scope: declared inside a routine (procedure, function, or block); visible only within that routine.

2.1. Comparison of Global and Local Variables

Aspect Global variable Local variable
Declaration locationOutside any routineInside a routine or block
LifetimeProgram start → program endRoutine entry → routine exit
VisibilityAll routines can accessOnly the defining routine can access
Memory usageAllocated onceAllocated each call (stack frame)
Typical useConfiguration data, shared counters, flagsTemporary calculations, loop counters, parameters

2.2. Advantages & Disadvantages

  • Global variables
    • Pros: convenient for data needed by many routines.
    • Cons: harder to trace changes, can cause hidden side‑effects, reduce modularity.
  • Local variables
    • Pros: improve readability, limit accidental modification, support modular design.
    • Cons: not available outside the routine (which is usually desirable).

3. Program Flow Structures (required by the syllabus)

3.1. Sequence

The default execution order – statements are performed one after another from top to bottom.

3.2. Selection (Decision making)

  • IF … THEN … ELSE … ENDIF
  • CASE … OF … ENDCASE (optional in the exam)

3.3. Iteration (Loops)

  • FOR i ← start TO end DO … ENDFOR – count‑controlled loop.
  • REPEAT … UNTIL condition – repeat‑until loop.
  • WHILE condition DO … ENDWHILE – condition‑controlled loop (allowed in the syllabus).

3.4. Totalling & Counting (common exam pattern)

Use a variable to accumulate a total or to count how many times a condition is true.

DECLARE total : INTEGER
total ← 0                         // initialise

FOR i ← 1 TO n DO
    total ← total + value[i]     // totalling
ENDFOR
OUTPUT "Total = ", total

3.5. String handling (required functions)

FunctionPurposeExample
LEN(str)Returns the length of a STRING.LEN("Hello") → 5
SUBSTRING(str, start, length)Extracts a part of a STRING.SUBSTRING("IGCSE", 2, 3) → "GCS"
UPPER(str) / LOWER(str)Converts case.UPPER("abc") → "ABC"
CONCAT(str1, str2)Joins two strings.CONCAT("Hi ", "Bob") → "Hi Bob"

4. Arrays (1‑D and 2‑D)

4.1. Declaration syntax

DECLARE scores : ARRAY[1:30] OF INTEGER          // 1‑D, lower bound 1
DECLARE matrix : ARRAY[1:5, 1:5] OF REAL          // 2‑D array

4.2. Accessing elements

  • Single subscript for 1‑D: scores[i]
  • Two subscripts for 2‑D: matrix[row, col]

4.3. Typical array operations

DECLARE total : INTEGER
total ← 0
FOR i ← 1 TO 30 DO
    total ← total + scores[i]        // totalling an array
ENDFOR
OUTPUT "Sum = ", total

4.4. Common pitfalls

  • Remember the lower bound used in the declaration (often 1 in the syllabus).
  • Do not exceed the upper bound – it causes a run‑time error.

5. Procedures and Functions (sub‑routines)

5.1. Declaration syntax

PROCEDURE CALC_AVG(scores : ARRAY[1:n] OF INTEGER, n : INTEGER)   // no return value
    DECLARE sum, i : INTEGER
    sum ← 0
    FOR i ← 1 TO n DO
        sum ← sum + scores[i]
    ENDFOR
    DECLARE avg : REAL
    avg ← sum / n
    OUTPUT "Average = ", avg
ENDPROCEDURE

5.2. Functions (return a value)

FUNCTION MAX(a : INTEGER, b : INTEGER) : INTEGER
    IF a > b THEN
        RETURN a
    ELSE
        RETURN b
    ENDIF
ENDFUNCTION

5.3. Parameter passing

  • Parameters are local to the routine – they hide any global variable with the same name (shadowing).
  • Values are passed by value (the routine receives a copy). To modify a global variable, either pass it as a parameter and assign the result, or use the global directly.

6. File Handling (exam‑style pseudocode)

Only the basic statements required by the syllabus are shown.

OPEN "scores.txt" FOR READ AS infile
DECLARE line : STRING
DECLARE total, count : INTEGER
total ← 0
count ← 0

REPEAT
    READLINE infile INTO line
    IF NOT EOF(infile) THEN
        DECLARE score : INTEGER
        score ← INTEGER(line)          // convert STRING to INTEGER
        total ← total + score
        count ← count + 1
    ENDIF
UNTIL EOF(infile)

CLOSE infile

IF count > 0 THEN
    DECLARE avg : REAL
    avg ← total / count
    OUTPUT "Average score = ", avg
ELSE
    OUTPUT "No data found."
ENDIF

7. Boolean Logic (truth tables & logic gates)

  • Boolean variables can be TRUE or FALSE.
  • Standard logical operators: AND, OR, NOT.

7.1. Truth tables (exam reference)

ABA AND BA OR BNOT A
TRUETRUETRUETRUEFALSE
TRUEFALSEFALSETRUEFALSE
FALSETRUEFALSETRUETRUE
FALSEFALSEFALSEFALSETRUE

7.2. Mapping to logic gates (optional for extra credit)

  • AND gate – output TRUE only if both inputs are TRUE.
  • OR gate – output TRUE if at least one input is TRUE.
  • NOT gate – inverts the input.

8. Input & Output (exam pseudocode)

INPUT studentMark          // reads a value into the variable studentMark
OUTPUT "Result: ", result // displays text followed by the value of result

The variable used with INPUT or OUTPUT must be declared in a scope that is visible at that point in the program.

9. Library Routines (commonly used in the exam)

  • ROUND(x) – rounds a REAL to the nearest INTEGER.
  • RANDOM(a, b) – returns a random INTEGER between a and b inclusive.
  • LEN(str) – length of a STRING.
  • SUBSTRING(str, start, length) – extracts part of a STRING.
  • UPPER(str) / LOWER(str) – case conversion.

10. Illustrative Examples in Different Languages

10.1. Python – using global

counter = 0                     # global variable

def increment():
    global counter              # refer to the global variable
    counter = counter + 1       # modify it

for i in range(5):
    increment()

print(counter)                  # prints 5

10.2. Java – static class variable (global to the class)

public class Counter {
    static int total = 0;               // global (class‑level) variable

    public static void addOne() {
        total = total + 1;              // can be used directly
    }

    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            addOne();
        }
        System.out.println(total);      // prints 5
    }
}

10.3. Pseudocode – global vs. local variable

CONSTANT PASS_MARK ← 40

DECLARE passCount : INTEGER
passCount ← 0                     // global counter

PROCEDURE CHECK_PASS(score : INTEGER)
    IF score >= PASS_MARK THEN
        passCount ← passCount + 1   // updates the global counter
        OUTPUT "Pass"
    ELSE
        OUTPUT "Fail"
    ENDIF
ENDPROCEDURE

DECLARE s : INTEGER
INPUT s
CALL CHECK_PASS(s)

OUTPUT "Number of passes = ", passCount

11. Best Practices (exam‑style checklist)

  1. Prefer local variables; use globals only when data must be shared by many routines.
  2. Give every identifier a clear, descriptive name that hints at its scope (e.g., globalTotal vs localTemp).
  3. Document each global variable with a comment stating its purpose and where it may be modified.
  4. Use constants for values that never change (e.g., conversion factors, limits).
  5. When a routine needs data from outside, pass it as a parameter rather than relying on globals.
  6. Keep the program structure simple: sequence → selection → iteration → totalling/counting.
  7. Indent code consistently; this helps to visualise scope.
  8. Check array bounds and initialise totals/counters before using them.

12. Common Pitfalls

  • Shadowing: Declaring a local variable with the same name as a global hides the global inside that routine.
  • Unintended accumulation: Forgetting to reset a global total before a new calculation leads to incorrect results.
  • Missing declaration: Omitting DECLARE or CONSTANT causes a syntax error in the exam.
  • Incorrect array bounds: Using 0 as the lower bound when the syllabus expects 1.
  • Wrong parameter order: When calling a procedure, ensure the arguments match the declared parameter list.
  • File handling errors: Not closing a file or reading past EOF.

13. Quick Quiz

  1. What will be printed by the following Python code?
    x = 10
    def foo():
        x = 5
        print(x)
    foo()
    print(x)
            
    • A) 5 5
    • B) 5 10
    • C) 10 5
    • D) 10 10
    Answer: B) 5 10 (the x inside foo is local; the global x remains 10.)
  2. Explain why using too many global variables can make debugging harder.
  3. Write pseudocode to read 20 integer scores from a file called "marks.txt", calculate the average, and output it. Use appropriate scope for variables.

14. Suggested Diagram

Flowchart illustrating a global variable total being accessed and updated by two separate procedures (ADD and DISPLAY), contrasted with a local variable temp that exists only inside ADD.

15. Key Take‑aways

  • Scope determines where a variable can be accessed – global (whole program) vs. local (single routine).
  • Use globals sparingly; they can cause hidden side‑effects.
  • Local variables improve modularity, readability and reduce bugs.
  • Declare every variable and constant with the required DECLARE/CONSTANT syntax.
  • Know the five basic data types, the allowed operators, and the core structures: sequence, selection, iteration, totalling/counting.
  • Be comfortable with arrays, procedures/functions, file handling, and basic string operations – all are explicitly tested in Paper 2.
  • Apply the best‑practice checklist to produce clear, maintainable, exam‑ready programs.

Create an account or Login to take a Quiz

44 views
0 improvement suggestions

Log in to suggest improvements to this note.