Constants

There are times in a computer program where you have a value that you need the computer to save that does not change or changes very rarely. Some examples are the value of π (3.14…) and the HST (the HST in Ontario is currently 13%, but it has changed once). When you have values like these, you do not want them to be saved as a variable (since they do not vary or change) but you place them in a constant.

Constants just like variables hold a particular value in memory for a programmer that will be used in the program. The difference is that the computer will not let the programmer change the value of a constant during the running of the program. This prevents errors from happening if the programmer accidently tries to change the value of a constant. It should always be declared, just as a variable is declared to warn the computer and people reading your code that it exists. Constants should be declared right before variables, so that they are prominent and easy to notice. Here are some examples of declaring constants:

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

using System;

/*
 * The Program class
 * Contains all methods for performing basic constants usage
*/
class Program {
    public static void Main (string[] args) {
        // constant definition
        const int ROOM_NUMBER = 212;
        const float HST = 0.13f;
        const string COUNTRY = "Canada";

        Console.WriteLine("Room: " + ROOM_NUMBER);
        Console.WriteLine(HST + "%");
        Console.WriteLine(COUNTRY);

        Console.WriteLine("\nDone.");
    }
}
../_images/replit.svg
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
// Copyright (c) 2020 Mr. Coxall All rights reserved.
//
// Created by: Mr. Coxall
// Created on: Sep 2020
// This program shows declaring constants

#include <iostream>

int main() {
    // constant definition
    const int ROOM_NUMBER = 212;
    const float HST = 0.13;
    const std::string COUNTRY = "Canada";

    std::cout << "Room: " << ROOM_NUMBER << std::endl;
    std::cout << HST << "%" << std::endl;
    std::cout << COUNTRY << std::endl;

    std::cout << "\nDone." << std::endl;
}
../_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
/*
 * This program shows declaring constants
 *
 * @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 of lives.
     */
    private static final int ROOM = 212;

    /**
     * Constant for HST.
     */
    private static final double HST = 0.13;

    /**
     * Constant for COUNTRY.
     */
    private static final String COUNTRY = "Canada";

    /**
     * Main entry point into program.
     * @param args nothing passed in
     */
    public static void main(final String[] args) {
        // output
        System.out.println("Room: " + ROOM);
        System.out.println(HST + "%");
        System.out.println(COUNTRY);

        System.out.println("\nDone.");
    }
}
../_images/replit.svg
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
/**
* Created by: Mr. Coxall
* Created on: Sep 2020
* This program shows declaring constants
*/

// constant definition
const ROOM = 212
const HST = 0.13
const COUNTRY = "Canada"

console.log("Room: " + ROOM)
console.log(HST + "%")
console.log(COUNTRY)

console.log("\nDone.")
../_images/replit.svg

In Python we normally create a seperate file called constants.py and place all our constants in it

constants.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
#!/usr/bin/env python3

# Created by: Mr. Coxall
# Created on: Sep 2020
# This contains constants

# constant definition
ROOM_NUMBER = 212
HST = 0.13
COUNTRY = "Canada"

main.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
#!/usr/bin/env python3

# Created by: Mr. Coxall
# Created on: Sep 2020
# This program shows declaring constants

import constants


def main():
    # then in the main program
    print("Room: " + str(constants.ROOM_NUMBER))
    print(str(constants.HST) + "%")
    print(constants.COUNTRY)

    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
# frozen_string_literal: true
#
# Created by: Mr. Coxall
# Created on: Sept 2020
# This program shows declaring constants

# A constant in Ruby is a type of variable which always starts with a capital letter.
# They can only be defined outside of methods, unless you use metaprogramming.
# By adding ".freeze", you will get a warning if you try and change a constant.
ROOM_NUMBER = 212.freeze
HST = 0.13.freeze
COUNTRY = "Canada".freeze

puts "Room: " + ROOM_NUMBER.to_s
puts HST.to_s + "%"
puts COUNTRY

puts "\nDone."
../_images/replit.svg
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
/**
 * Class Constants.
 * Created by: Mr. Coxall
 * Created on: Sep 2020
 * This program shows declaring constants
 */

// In Swift we normally DO NOT capitalize all the letters in a constant name.
// By default everything is declared as a constant, unless it needs to be a variable.
let roomNumber = 212
let HST = 0.13
let country = "Canada"

print("Room: " +  String(roomNumber))
print(String(HST) + "%")
print(country)

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