Local & Global Variables

What Are Global and Local Variables?

Global variables are accessible throughout an entire program, while local variables are restricted to the function or block where they are declared.

Understanding variable scope is crucial for avoiding errors and optimising memory usage.

Variable Scope and Data Types

Variable Type Scope Example
Global Variable Accessible throughout the entire program. global counter (Python)
static int count; (Java)
Local Variable Accessible only within the function or block where it is defined. sum = 0 (Python)
int sum = 0; (Java)

Common Data Types

Data Type Description Example
Boolean Stores true or false values. is_valid = True (Python)
boolean isValid = true; (Java)
Character (char) Stores a single character. letter = 'A' (Python)
char letter = 'A'; (Java)
Integer Stores whole numbers. age = 25 (Python)
int age = 25; (Java)
Decimal (float/double) Stores numbers with decimal points. price = 19.99 (Python)
double price = 19.99; (Java)
String Stores sequences of characters. name = "Alice" (Python)
String name = "Alice"; (Java)

Example: increment() function and trace table

global_count = 0

# def represents the start of a subroutine
# in these code blocks, variables are 'local' (unless otherwise declared)
def increment():
    global global_count
    local_count = 5
    global_count += local_count
    return global_count

newVal = increment()
print("Total count:", newVal)

# Any part of the script can access Global variables ...
newVal2 = global_count + 1
print("Total count:", newVal2)

# ... but not Local variables
# (crashes here)
newVal3 = local_count + 2
print("Total count:", newVal3)
public class ScopeExample {

  private static int globalCount = 0;

// public static int marks the start of a method that returns an int
// in these code blocks, variables are 'local' (unless class-level)
  public static int increment() {
    int localCount = 5;
    globalCount += localCount;
    return globalCount;
  }

  public static void main(String[] args) {
    int newVal = increment();
    System.out.println("Total count: " + newVal);

    // Any part of the class can access global (static) variables…
    int newVal2 = globalCount + 1;
    System.out.println("Total count: " + newVal2);

    // …but not local variables (compile error if uncommented)
    // int newVal3 = localCount + 2;
    // System.out.println("Total count: " + newVal3);
  }
}

Trace Table for increment() Function

Notice how a row is used. Generally, sequences of instructions use the same line.

The call and return columns are to highlight when local variables are being processed.

Call Return global_count local_count newVal newVal2 newVal3 Output
0
increment()
55
55Total count: 5
6Total count: 6
Error

Example: difference(a, b) function and trace table

def difference(a, b):
    diff = a - b
    return diff

mainVar = 10
for i in range(1, 4):
    theDiff = difference(mainVar, i)
    print("theDiff =", theDiff)
public class DifferenceExample {

  public static int difference(int a, int b) {
    int diff = a - b;
    return diff
  }

  public static void main(String[] args) {
    int mainVar = 10;
    for (int i = 1; i <= 3; i++) {
      int theDiff = difference(mainVar, i);
      System.out.println("theDiff = " + theDiff);
    }
  }
}

Trace Table for difference() Function

Notice how a row is used. Generally, a loop iteration has its own line.

The call and return columns are to highlight when local variables are being processed.

Call Return mainVar i diff theDiff Output
10
1
difference(mainVar, i)
9
99theDiff = 9
2
difference(mainVar, i)
8
88theDiff = 8
3
difference(mainVar, i)
7
77theDiff = 7

Challenges in Managing Variables

  • Variable Shadowing: Local variables may have the same names as global ones, which can make program maintenance more difficult, leading to unexpected bugs.
  • Memory Management: Excessive global variables can bloat memory usage.
  • Data Integrity: Global variables can be modified from anywhere, risking inconsistent state.

 Key Takeaways

  • Global variables are accessible program-wide; local variables are limited to their defining block or function.
  • Common data types include Boolean, char, integer, decimal, and string.
  • Proper scope management prevents errors and optimises resource use.
  • Trace tables and flowcharts help visualise how variables change during execution.