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:

// Copyright (c) 2020 Mr. Coxall All rights reserved.
//
// Created by: Mr. Coxall
// Created on: June 2020
// This program shows declaring constants

#include <stdio.h>

int main() {
    // constant definition
    const int NUMBER_OF_LIVES = 3;
    const double HST = 0.13;
}
// Created by: Mr. Coxall
// Created on: June 2020
// This program shows declaring constants

package main

func main() {
    // constant definition
    const NUMBER_OF_LIVES int = 3
    const HST float32 = 0.13
}
/**
 * Class Constants.
 * Created by: Mr. Coxall
 * Created on: June 2020
 * This program shows declaring constants
 */
public class Constants {
  // constant definition
  private static int NUMBER_OF_LIVES = 3;
  private static double HST = 0.13;

  public static void main(String[] args) {
    // some code ...
  }
}
/**
 * Created by: Mr. Coxall
 * Created on: June 2020
 * This program shows declaring constants
 */

// constant definition
const NUMBER_OF_LIVES = 3;
const HST = 0.13;
--> file named: constants.py
# constant definition
# Note: in python ususally constants are declared in a seperate module
#   In this example the module is called "constants" and would have the following lines of code:

NUMBER_OF_LIVES = 3
HST = 0.13

--> file named: constants_example_code.py
#!/usr/bin/env python3

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

import constants


def main():
    # then in the main program

    constants.NUMBER_OF_LIVES
    constants.HST


if __name__ == "__main__":
    main()
#!/usr/bin/env ruby

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

NUMBER_OF_LIVES = 3
HST = 0.13
/**
 * Class Constants.
 * Created by: Mr. Coxall
 * Created on: June 2020
 * This program shows declaring constants
 */

let numberOfLives = 3
let HST = 0.13