Local & Global Variables (CIE IGCSE Computer Science)

Revision Note

Test Yourself
Becci Peters

Expertise

Computer Science

Local & Global Variables

  • A local variable is a variable that is declared inside a subroutine and can only be accessed from within that subroutine
  • A global variable is a variable that is declared outside of a subroutine and can be accessed from anywhere in the program
  • Global variables can be used to pass data between different subroutine
  • Overuse of global variables can make a program difficult to understand and debug and is therefore discouraged as it’s considered bad practice 

Pseudocode example:

global total_score

FUNCTION calculate_average(num1: INTEGER, num2: INTEGER)

    average (num1 + num2) / 2

    RETURN average

END FUNCTION

total_score 0

PROCEDURE add_score(score: INTEGER)

    total_score total_score + score

END PROCEDURE

Python example:

def calculate_average(num1, num2):

    average = (num1 + num2) / 2

    return average

total_score = 0

def add_score(score):

    global total_score

    total_score = total_score + score

Java example:

static int totalScore = 0;

public static void main(String args[]) {

    double average = calculateAverage(5, 7);

    System.out.println("Average: " + average);

    addScore(10);

    System.out.println("Total score: " + totalScore);

}

public static double calculateAverage(int num1, int num2) {

    double average = (num1 + num2) / 2.0;

    return average;

}

public static void addScore(int score) {

    totalScore = totalScore + score;

}

Visual Basic example:

Dim totalScore As Integer = 0

Dim average As Double = CalculateAverage(5, 7)

        Console.WriteLine("Average: " & average)

        AddScore(10)

        Console.WriteLine("Total score: " & totalScore)

Function CalculateAverage(num1 As Integer, num2 As Integer) As Double

        Dim average As Double = (num1 + num2) / 2.0

        Return average

End Function

Sub AddScore(score As Integer)

        totalScore = totalScore + score

End Sub

You've read 0 of your 0 free revision notes

Get unlimited access

to absolutely everything:

  • Downloadable PDFs
  • Unlimited Revision Notes
  • Topic Questions
  • Past Papers
  • Model Answers
  • Videos (Maths and Science)

Join the 100,000+ Students that ❤️ Save My Exams

the (exam) results speak for themselves:

Did this page help you?

Becci Peters

Author: Becci Peters

Becci has been a passionate Computing teacher for over 9 years, teaching Computing across the UK helping to engage, interest and develop confidence in the subject at all levels. Working as a Head of Department and then as an educational consultant, Becci has advised schools in England, where her role was to support and coach teachers to improve Computing teaching for all. Becci is also a senior examiner for multiple exam boards covering GCSE & A-level. She has worked as a lecturer at a university, lecturing trainee teachers for Computing.