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// Copyright (c) 2020 St. Mother Teresa HS All rights reserved.
2//
3// Created by: Mr. Coxall
4// Created on: Sep 2020
5// This program shows how local and global variables work
6
7#include <stdio.h>
8
9// global variable
10int variableX = 25;
11
12void localVariable() {
13 // this shows what happens with local variables
14 int variableX = 10;
15 int variableY = 30;
16 int variableZ;
17
18 variableX = variableX + 1;
19 variableZ = variableX + variableY;
20
21 printf("Local variableX, variableY, variableZ: %d + %d = %d\n", variableX, variableY, variableZ);
22}
23
24void globalVariable() {
25 // this shows what happens with global variables
26 int variableY = 30;
27 int variableZ;
28
29 variableX = variableX + 1;
30 variableZ = variableX + variableY;
31
32 printf("Local variableX, variableY, variableZ: %d + %d = %d\n", variableX, variableY, variableZ);
33}
34
35int main() {
36 // this function calls local and global
37 localVariable();
38 globalVariable();
39
40 printf("\nDone.\n");
41 return 0;
42}
1// Copyright (c) 2020 St. Mother Teresa HS All rights reserved.
2//
3// Created by: Mr. Coxall
4// Created on: Sep 2020
5// This program shows how local and global variables work
6
7#include <iostream>
8
9// global variable
10int variableX = 25;
11
12void localVariable() {
13 // this shows what happens with local variables
14 int variableX = 10;
15 int variableY = 30;
16 int variableZ;
17
18 variableX = variableX + 1;
19 variableZ = variableX + variableY;
20
21 std::cout << "Local variableX, variableY, variableZ: " << variableX
22 << " + " << variableY << " = " << variableZ << std::endl;
23}
24
25void globalVariable() {
26 // this shows what happens with global variables
27 int variableY = 30;
28 int variableZ;
29
30 variableX = variableX + 1;
31 variableZ = variableX + variableY;
32
33 std::cout << "Local variableX, variableY, variableZ: " << variableX
34 << " + " << variableY << " = " << variableZ << std::endl;
35}
36
37int main() {
38 // this function calls local and global
39 localVariable();
40 globalVariable();
41
42 std::cout << "\nDone. " << std::endl;
43}
1/* Created by: Mr. Coxall
2 * Created on: Sep 2020
3 * This program shows how local and global variables work
4*/
5
6using System;
7
8/*
9 * The Program class
10 * Contains all methods for performing how local and global variables work
11*/
12class Program {
13
14 // global variable
15 public static int variableX = 25;
16
17 static void localVariable() {
18 // this shows what happens with local variables
19 int variableX = 10;
20 int variableY = 30;
21 int variableZ;
22
23 variableX = variableX + 1;
24 variableZ = variableX + variableY;
25
26 Console.WriteLine ($"Local variableX, variableY, variableZ: {variableX} + {variableY} = {variableZ}");
27 }
28
29 static void globalVariable() {
30 // this shows what happens with global variables
31 int variableY = 30;
32 int variableZ;
33
34 variableX = variableX + 1;
35 variableZ = variableX + variableY;
36
37 Console.WriteLine ($"Local variableX, variableY, variableZ: {variableX} + {variableY} = {variableZ}");
38 }
39
40 public static void Main (string[] args) {
41 // this function calls local and global
42 localVariable();
43 globalVariable();
44
45 Console.WriteLine ("\nDone.");
46 }
47}
1/**
2 * Created by: Mr. Coxall
3 * Created on: Sep 2020
4 * This program shows how local and global variables work
5 */
6//nolint
7package main
8
9import "fmt"
10
11// global variable
12var variableX = 25
13
14func localVariable() {
15 // this shows what happens with local variables
16 var variableX = 10
17 var variableY = 30
18
19 variableX++
20 variableZ := variableX + variableY
21
22 fmt.Println("Local variableX, variableY, variableZ:", variableX, "+", variableY, "=", variableZ)
23}
24
25func globalVariable() {
26 // this shows what happens with global variables
27 variableY := 30
28
29 variableX++
30 variableZ := variableX + variableY
31
32 fmt.Println("Global variableX, variableY, variableZ:", variableX, "+", variableY, "=", variableZ)
33}
34
35func main() {
36 localVariable()
37 globalVariable()
38
39 fmt.Println("\nDone.")
40}
1/*
2 * This program shows how local and global variables work
3 *
4 * @author Mr Coxall
5 * @version 1.0
6 * @since 2020-09-01
7 */
8
9final class Main {
10 private Main() {
11 // Prevent instantiation
12 // Optional: throw an exception e.g. AssertionError
13 // if this ever *is* called
14 throw new IllegalStateException("Cannot be instantiated");
15 }
16
17 // global variable
18 static int variableX = 25;
19
20 /**
21 * The localVariable() function.
22 *
23 * @param nil
24 * @return nil
25 */
26 public static void localVariable() {
27 int variableX = 10;
28 int variableY = 30;
29 int variableZ;
30
31 variableX = variableX + 1;
32 variableZ = variableX + variableY;
33
34 System.out.println(
35 "Local variableX, variableY, variableZ: "
36 + variableX
37 + " + "
38 + variableY
39 + " = "
40 + variableZ);
41 }
42
43 /**
44 * The globalVariable() function.
45 *
46 * @param nil
47 * @return nil
48 */
49 public static void globalVariable() {
50 int variableY = 30;
51 int variableZ;
52
53 variableX = variableX + 1;
54 variableZ = variableX + variableY;
55
56 System.out.println(
57 "Local variableX, variableY, variableZ: "
58 + variableX
59 + " + "
60 + variableY
61 + " = "
62 + variableZ);
63 }
64
65 /**
66 * Main entry point into program.
67 *
68 * @param args nothing passed in
69 */
70 public static void main(final String[] args) {
71 // this function calls local and global
72 localVariable();
73 globalVariable();
74
75 System.out.println("\nDone.");
76 }
77}
1/* Created by: Mr. Coxall
2 * Created on: Sep 2020
3 * This program shows how local and global variables work
4*/
5
6// global variable
7var variableX = 25
8
9function localVariable() {
10 // this shows what happens with local variables
11 let variableX = 10
12 let variableY = 30
13
14 variableX = variableX + 1
15 let variableZ = variableX + variableY
16
17 console.log("Local variableX, variableY, variableZ: " + variableX + " + " + variableY + " = " + variableZ)
18}
19
20function globalVariable() {
21 // this shows what happens with global variables
22 let variableY = 30
23
24 variableX = variableX + 1
25 let variableZ = variableX + variableY
26
27 console.log("Local variableX, variableY, variableZ: " + variableX + " + " + variableY + " = " + variableZ)
28}
29
30localVariable()
31globalVariable()
32
33console.log("\nDone.")
1#!/usr/bin/env python3
2"""
3Created by: Mr. Coxall
4Created on: Sep 2020
5This module shows how local and global variables work
6"""
7
8# global variable
9variable_x = 25
10
11
12def local_variable() -> None:
13 """The local_variable() function creates local variables, returns None."""
14 variable_x = 10
15 variable_y = 30
16
17 variable_x = variable_x + 1
18 variable_z = variable_x + variable_y
19
20 print(f"Local variable: {variable_x} + {variable_y} = {variable_z}")
21
22
23def global_variable() -> None:
24 """The global_variable() function uses a global variable, returns None."""
25 global variable_x
26 variable_y = 30
27
28 variable_x = variable_x + 1
29 variable_z = variable_x + variable_y
30
31 print(f"Global variable: {variable_x} + {variable_y} = {variable_z}")
32
33
34def main() -> None:
35 """The main() function shows local and global variables, returns None."""
36 local_variable()
37 global_variable()
38
39 print("\nDone.")
40
41
42if __name__ == "__main__":
43 main()
Example Output
