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-allocate 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
/* Created by: Mr. Coxall
 * Created on: Sep 2020
 * This program shows assingment statements
*/

using System;

/*
 * The Program class
 * Contains all methods for performing basic variable usage
*/
class Program {
    public static void Main (string[] args) {
        // variable definition
        int numberOfStudents = 2;
        float width = 32.5F;
        float length = 10.0F;
        float areaOfRectangle = 0F;
        string someWords1 = "Hello";
        string someWords2 = "Wordl!";
        string helloWorld = null;

        // using assignment statements
        numberOfStudents = numberOfStudents + 5;
        areaOfRectangle = length * width;
        helloWorld = someWords1 + ", " + someWords2; 

        // output
        Console.WriteLine ("The number of students is: " + numberOfStudents);
        Console.WriteLine ("The area of a rectangle is: " + areaOfRectangle + " cm²");
        Console.WriteLine (helloWorld);

        Console.WriteLine ("\nDone.");
    }
}
../_images/replit.svg
../_images/replit.svg
 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
/*
 * This program program shows assingment statements
 *
 * @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");
    }

    /**
     * Constant number TWO.
     */
    private static final int TWO = 2;

    /**
     * Constant number THIRTY_TWO_POINT_FIVE.
     */
    private static final float THIRTY_TWO_POINT_FIVE = 32.5F;

    /**
     * Constant number TEN.
     */
    private static final float TEN = 10.0F;

        /**
     * Constant number FIVE.
     */
    private static final int FIVE = 5;

    /**
     * Main entry point into program.
     * @param args nothing passed in
     */
    public static void main(final String[] args) {
        // variable definition
        int numberOfStudents = TWO;
        float width = THIRTY_TWO_POINT_FIVE;
        float length = TEN;
        float areaOfRectangle = 0F;
        String someWords1 = "Hello";
        String someWords2 = "Wordl!";
        String helloWorld = null;

        // using assignment statements
        numberOfStudents = numberOfStudents + FIVE;
        areaOfRectangle = length * width;
        helloWorld = someWords1 + ", " + someWords2;

        // output
        System.out.println("The number of students is: " + numberOfStudents);
        System.out.println("The area of a rectangle is: "
                           + areaOfRectangle + " cm²");
        System.out.println(helloWorld);

        System.out.println("\nDone.");
    }
}
../_images/replit.svg
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/* Created by: Mr. Coxall
 * Created on: Sep 2020
 * This program shows assingment statements
*/

// variable definition
numberOfStudents = 2
width = 32.5
length = 10.0
someWords1 = "Hello"
someWords2 = "Wordl!"

// using assignment statements
numberOfStudents = numberOfStudents + 5
areaOfRectangle = length * width
helloWorld = someWords1 + ", " + someWords2

// output
console.log("The number of students is: " + numberOfStudents)
console.log("The area of a rectangle is: " + areaOfRectangle + " cm²")
console.log(helloWorld)

console.log("\nDone.")
../_images/replit.svg
 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
#!/usr/bin/env python3

# Created by: Mr. Coxall
# Created on: Sep 2020
# This program shows assingment statements


def main():
    # variable definition
    number_of_students = 2
    width = 32.5
    length = 10.0
    some_words1 = "Hello"
    some_words2 = "Wordl!"

    # using assignment statements
    number_of_students = number_of_students + 5
    area_of_rectangle = length * width
    hello_world = some_words1 + ", " + some_words2

    # output
    print("The number of students is: " + str(number_of_students))
    print("The area of a rectangle is: " + str(area_of_rectangle) + " cm²")
    print(hello_world)

    print("\nDone.")


if __name__ == "__main__":
    main()
../_images/replit.svg
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# frozen_string_literal: true
#
# Created by: Mr. Coxall
# Created on: Sept 2020
# This program shows assingment statements

# variable definition
number_of_students = 2
width = 32.5
length = 10.0
some_words1 = "Hello"
some_words2 = "Wordl!"

# using assignment statements
number_of_students = number_of_students + 5
area_of_rectangle = length * width
hello_world = some_words1 + ", " + some_words2

# output
puts"The number of students is: " + number_of_students.to_s
puts"The area of a rectangle is: " + area_of_rectangle.to_s + " cm²"
puts hello_world

puts "\nDone."
../_images/replit.svg
 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
/**
 * Class Variables.
 * Created by: Mr. Coxall
 * Created on: Sep 2020
 * This program shows assingment statements
 */

// variable definition
var numberOfStudents = 2
let width = 32.5
let length = 10.0
let someWords1 = "Hello"
let someWords2 = "Wordl!"

var area: Double
var helloWorld: String

// using assignment statements
numberOfStudents = numberOfStudents + 5
area = length * width
helloWorld = someWords1 + ", " + someWords2

// output
print("The number of students is: " + String(numberOfStudents))
print("The area of a rectangle is: " + String(area) + " cm²")
print(helloWorld)

print("\nDone.")
../_images/replit.svg