Skip to main content
Logo image

Section 2.8 Constant Variables

Learning Objective:
  • Student will be able to identify when to use a constant variable
We have mentioned earlier that variables are changeable meaning you can change the value a variable is holding at any point in the program’s execution. What if you want to keep a variable at a constant value throughout the program? You don’t want to accidentally change it. You can then use a constant variable. A constant variable is a special type of variable that can not be changed while the program is executing. For example, let’s go back to the example we were talking about earlier. Let’s assume that your school only had three classrooms, class1, class2, and class3. And the use of the total number of classrooms comes up frequently in the program implementation. We can use a constant variable in its place since.
  1. We do not need to change the value of the total number of classrooms while the program is executing.
  2. If we replace all the places where we used to have the total number of classrooms “3” (number literal, A number literal is a number that appears fixed in a program. It is not a variable) with a constant if the number of classrooms ever changed to 4 or another number all we have to do is change the value of the constant before the program is run and it will be reflected in all places.
Constants are usually noted by naming the variable in all caps. For example;
Const Integer TOTAL_CLASSROOMS

Exercises Exercises

1.

Give a scenario where using a constant is more appropriate
You have attempted of activities on this page.