Scope of Variables¶
Where a variable is declared is important because it determines its scope. The scope refers to where it is visible or can be used within a program. Usually you would declare a variable at the beginning of a function (for example a click event on a button or menu or the “main” function). Since it is declared at the beginning of a function, it can only be used within that funtion. Once the flow of your program exits this funtion, the variable is removed from memory (actually it is just de-allocated most likely) and can no longer be used. This type of variable is referred to as a local variable. Any other function in your program can not use or refer to this variable.
What if for some reason you needed a variable to be accessible to several different functions within a single program. In this case declaring it within a single function is no good. Another option is to declare the variable at the top of the form class or module, just before any function. If this is done then any function within that program can see and use this variable. This type of variable is called a global variable. Global variables should only be used when absolutely necessary; if only one function needs a variable, it should be declared within the function. This is good programming style and also saves computer memory. The following is an example where you can see variables with the same name, being used as global and local variables. Type it in and follow the variables by stepping through the program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 // Copyright (c) 2020 St. Mother Teresa HS All rights reserved. // // Created by: Mr. Coxall // Created on: Sep 2020 // This program shows how local and global variables work #include <stdio.h> // global variable int variableX = 25; void localVariable() { // this shows what happens with local variables int variableX = 10; int variableY = 30; int variableZ; variableX = variableX + 1; variableZ = variableX + variableY; printf("Local variableX, variableY, variableZ: %d + %d = %d\n", variableX, variableY, variableZ); } void globalVariable() { // this shows what happens with global variables int variableY = 30; int variableZ; variableX = variableX + 1; variableZ = variableX + variableY; printf("Local variableX, variableY, variableZ: %d + %d = %d\n", variableX, variableY, variableZ); } int main() { // this function calls local and global localVariable(); globalVariable(); printf("\nDone.\n"); return 0; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 // Copyright (c) 2020 St. Mother Teresa HS All rights reserved. // // Created by: Mr. Coxall // Created on: Sep 2020 // This program shows how local and global variables work #include <iostream> // global variable int variableX = 25; void localVariable() { // this shows what happens with local variables int variableX = 10; int variableY = 30; int variableZ; variableX = variableX + 1; variableZ = variableX + variableY; std::cout << "Local variableX, variableY, variableZ: " << variableX << " + " << variableY << " = " << variableZ << std::endl; } void globalVariable() { // this shows what happens with global variables int variableY = 30; int variableZ; variableX = variableX + 1; variableZ = variableX + variableY; std::cout << "Local variableX, variableY, variableZ: " << variableX << " + " << variableY << " = " << variableZ << std::endl; } int main() { // this function calls local and global localVariable(); globalVariable(); std::cout << "\nDone. " << std::endl; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 /* Created by: Mr. Coxall * Created on: Sep 2020 * This program shows how local and global variables work */ using System; /* * The Program class * Contains all methods for performing how local and global variables work */ class Program { // global variable public static int variableX = 25; static void localVariable() { // this shows what happens with local variables int variableX = 10; int variableY = 30; int variableZ; variableX = variableX + 1; variableZ = variableX + variableY; Console.WriteLine ($"Local variableX, variableY, variableZ: {variableX} + {variableY} = {variableZ}"); } static void globalVariable() { // this shows what happens with global variables int variableY = 30; int variableZ; variableX = variableX + 1; variableZ = variableX + variableY; Console.WriteLine ($"Local variableX, variableY, variableZ: {variableX} + {variableY} = {variableZ}"); } public static void Main (string[] args) { // this function calls local and global localVariable(); globalVariable(); Console.WriteLine ("\nDone."); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 /** * Created by: Mr. Coxall * Created on: Sep 2020 * This program shows how local and global variables work */ //nolint package main import "fmt" // global variable var variableX = 25 func localVariable() { // this shows what happens with local variables var variableX = 10 var variableY = 30 variableX++ variableZ := variableX + variableY fmt.Println("Local variableX, variableY, variableZ:", variableX, "+", variableY, "=", variableZ) } func globalVariable() { // this shows what happens with global variables variableY := 30 variableX++ variableZ := variableX + variableY fmt.Println("Global variableX, variableY, variableZ:", variableX, "+", variableY, "=", variableZ) } func main() { localVariable() globalVariable() fmt.Println("\nDone.") }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 /* * This program shows how local and global variables work * * @author Mr Coxall * @version 1.0 * @since 2020-09-01 */ final class Main { private Main() { // Prevent instantiation // Optional: throw an exception e.g. AssertionError // if this ever *is* called throw new IllegalStateException("Cannot be instantiated"); } // global variable static int variableX = 25; /** * The localVariable() function. * * @param nil * @return nil */ public static void localVariable() { int variableX = 10; int variableY = 30; int variableZ; variableX = variableX + 1; variableZ = variableX + variableY; System.out.println( "Local variableX, variableY, variableZ: " + variableX + " + " + variableY + " = " + variableZ); } /** * The globalVariable() function. * * @param nil * @return nil */ public static void globalVariable() { int variableY = 30; int variableZ; variableX = variableX + 1; variableZ = variableX + variableY; System.out.println( "Local variableX, variableY, variableZ: " + variableX + " + " + variableY + " = " + variableZ); } /** * Main entry point into program. * * @param args nothing passed in */ public static void main(final String[] args) { // this function calls local and global localVariable(); globalVariable(); System.out.println("\nDone."); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 /* Created by: Mr. Coxall * Created on: Sep 2020 * This program shows how local and global variables work */ // global variable var variableX = 25 function localVariable() { // this shows what happens with local variables let variableX = 10 let variableY = 30 variableX = variableX + 1 let variableZ = variableX + variableY console.log("Local variableX, variableY, variableZ: " + variableX + " + " + variableY + " = " + variableZ) } function globalVariable() { // this shows what happens with global variables let variableY = 30 variableX = variableX + 1 let variableZ = variableX + variableY console.log("Local variableX, variableY, variableZ: " + variableX + " + " + variableY + " = " + variableZ) } localVariable() globalVariable() console.log("\nDone.")
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 #!/usr/bin/env python3 """ Created by: Mr. Coxall Created on: Sep 2020 This module shows how local and global variables work """ # global variable variable_x = 25 def local_variable() -> None: """The local_variable() function creates local variables, returns None.""" variable_x = 10 variable_y = 30 variable_x = variable_x + 1 variable_z = variable_x + variable_y print(f"Local variable: {variable_x} + {variable_y} = {variable_z}") def global_variable() -> None: """The global_variable() function uses a global variable, returns None.""" global variable_x variable_y = 30 variable_x = variable_x + 1 variable_z = variable_x + variable_y print(f"Global variable: {variable_x} + {variable_y} = {variable_z}") def main() -> None: """The main() function shows local and global variables, returns None.""" local_variable() global_variable() print("\nDone.") if __name__ == "__main__": main()