Use local variables

Local and Global Variables

Every variable in a program has a scope - the region of code where it exists and can be used. In the previous benchmark, you saw that local variables are confined to the subroutine that declared them. The alternative is a global variable: one declared outside all subroutines, at the top level of the program, so that it is accessible from anywhere - including every subroutine.

Local variableGlobal variable
DeclaredInside a subroutineOutside all subroutines
Accessible fromThat subroutine onlyAnywhere in the program
LifetimeWhile the subroutine executesEntire program execution
RiskLow - isolatedHigher - any subroutine can change it

Why Local Variables are Good Practice

Global variables are not wrong in every situation, but using them unnecessarily introduces serious risks. The three examples below show a local variable working safely, a global variable causing a hard-to-find bug, and the same program corrected by switching to a local variable. Select a tab, then choose a language.

Here, discount is a local variable inside applyDiscount(). Calculating a different discount elsewhere in the program has no effect on this subroutine - each calculation is completely isolated.

# Python -- local variable: isolated, cannot be accidentally changed elsewhere
def applyDiscount(price):
    discount = price * 0.1      # local variable -- only exists here
    return price - discount

def applyTax(price):
    discount = price * 0.2      # entirely separate local variable -- same name, no clash
    return price + discount

print(applyDiscount(100))       # prints 90.0
print(applyTax(100))            # prints 120.0
# the two "discount" variables never interfere with each other
' VB.NET -- local variable: isolated, cannot be accidentally changed elsewhere
Function applyDiscount(ByVal price As Double) As Double
    Dim discount As Double = price * 0.1    ' local variable -- only exists here
    Return price - discount
End Function

Function applyTax(ByVal price As Double) As Double
    Dim discount As Double = price * 0.2    ' entirely separate local variable
    Return price + discount
End Function

Console.WriteLine(applyDiscount(100))       ' prints 90.0
Console.WriteLine(applyTax(100))            ' prints 120.0
' the two "discount" variables never interfere with each other
// C# -- local variable: isolated, cannot be accidentally changed elsewhere
static double ApplyDiscount(double price)
{
    double discount = price * 0.1;   // local variable -- only exists here
    return price - discount;
}

static double ApplyTax(double price)
{
    double discount = price * 0.2;   // entirely separate local variable
    return price + discount;
}

Console.WriteLine(ApplyDiscount(100));  // prints 90.0
Console.WriteLine(ApplyTax(100));       // prints 120.0
// the two "discount" variables never interfere with each other

Here, discount is declared as a global variable. The subroutine applyDiscount() expects to use 10%, but applyTax() accidentally overwrites the global discount with a different value. When applyDiscount() is called a second time, it uses the wrong value. This type of bug can be very difficult to trace in a large program.

# Python -- global variable: unintended side effect
discount = 0.1              # global variable: accessible everywhere

def applyDiscount(price):
    global discount
    return price - (price * discount)   # uses global discount (0.1 = 10%)

def applyTax(price):
    global discount
    discount = 0.2           # OVERWRITES the global variable -- side effect!
    return price + (price * discount)

print(applyDiscount(100))   # prints 90.0 -- correct so far
applyTax(100)               # this call silently changes discount to 0.2
print(applyDiscount(100))   # prints 80.0 -- WRONG: discount has been corrupted
' VB.NET -- global variable: unintended side effect
Dim discount As Double = 0.1    ' module-level (global) variable

Function applyDiscount(ByVal price As Double) As Double
    Return price - (price * discount)   ' uses global discount (0.1 = 10%)
End Function

Function applyTax(ByVal price As Double) As Double
    discount = 0.2                      ' OVERWRITES the global variable -- side effect!
    Return price + (price * discount)
End Function

Console.WriteLine(applyDiscount(100))   ' prints 90.0 -- correct so far
applyTax(100)                           ' this call silently changes discount to 0.2
Console.WriteLine(applyDiscount(100))   ' prints 80.0 -- WRONG: discount has been corrupted
// C# -- global variable: unintended side effect
static double discount = 0.1;   // class-level (global) variable

static double ApplyDiscount(double price)
{
    return price - (price * discount);  // uses global discount (0.1 = 10%)
}

static double ApplyTax(double price)
{
    discount = 0.2;                     // OVERWRITES the global variable -- side effect!
    return price + (price * discount);
}

Console.WriteLine(ApplyDiscount(100));  // prints 90.0 -- correct so far
ApplyTax(100);                          // this call silently changes discount to 0.2
Console.WriteLine(ApplyDiscount(100));  // prints 80.0 -- WRONG: discount has been corrupted

The fix is straightforward: each subroutine declares its own local discount variable rather than reading from or writing to a shared global. The two calculations are now fully independent, and the bug cannot occur.

# Python -- fixed: local variables prevent the side effect
def applyDiscount(price):
    discount = price * 0.1      # local -- belongs to this subroutine only
    return price - discount

def applyTax(price):
    discount = price * 0.2      # local -- completely separate variable
    return price + discount

print(applyDiscount(100))       # prints 90.0 -- correct
applyTax(100)                   # no side effect on applyDiscount
print(applyDiscount(100))       # prints 90.0 -- still correct
' VB.NET -- fixed: local variables prevent the side effect
Function applyDiscount(ByVal price As Double) As Double
    Dim discount As Double = price * 0.1    ' local -- belongs to this subroutine only
    Return price - discount
End Function

Function applyTax(ByVal price As Double) As Double
    Dim discount As Double = price * 0.2    ' local -- completely separate variable
    Return price + discount
End Function

Console.WriteLine(applyDiscount(100))       ' prints 90.0 -- correct
applyTax(100)                               ' no side effect on applyDiscount
Console.WriteLine(applyDiscount(100))       ' prints 90.0 -- still correct
// C# -- fixed: local variables prevent the side effect
static double ApplyDiscount(double price)
{
    double discount = price * 0.1;  // local -- belongs to this subroutine only
    return price - discount;
}

static double ApplyTax(double price)
{
    double discount = price * 0.2;  // local -- completely separate variable
    return price + discount;
}

Console.WriteLine(ApplyDiscount(100));  // prints 90.0 -- correct
ApplyTax(100);                          // no side effect on ApplyDiscount
Console.WriteLine(ApplyDiscount(100));  // prints 90.0 -- still correct

Reasons to Prefer Local Variables

  • No unintended side effects: a local variable cannot be accidentally modified by another subroutine, because it is invisible outside its own subroutine.
  • Easier to test and debug: a subroutine using only local variables (and its parameters) is self-contained - its behaviour depends only on what is passed in, not on the state of the rest of the program.
  • Avoids naming conflicts: local variables with the same name in different subroutines are entirely separate, so there is no need to invent unique names across the whole program.
  • Memory efficiency: local variables are destroyed when the subroutine ends, so they do not occupy memory for the entire lifetime of the program.

 Key Takeaways

  • A local variable is declared inside a subroutine and only exists and is accessible there; a global variable is declared at program level and is accessible everywhere.
  • Using local variables prevents unintended side effects: one subroutine cannot accidentally read or overwrite a variable belonging to another.
  • Subroutines that rely only on local variables and parameters are self-contained, making them much easier to test, debug, and reuse.
  • Good practice is to use local variables by default and only use global variables when data genuinely needs to be shared across many subroutines throughout the program.