You are here

Understanding Constants

5 February, 2015 - 14:42

Various textbooks describe constants using different terminology. Added to the complexity are the explainations from various industry professionals will vary greatly. Let's see if we can clear it up.

A constant is a data item whose value cannot change during the program's execution. Thus, as its name implies their value is constant.

A variable is a data item whose value can change during the program's execution. Thus, as its name implies their value can vary.

Constants are used in three ways within C++. They are:

  1. literal constant
  2. defined constant
  3. memory constant

A literal constant is a value you type into your program wherever it is needed. Examples include the constants used for initializing a variable and constants used in lines of code:

Example 3.1: Literal Constants

int age = 2l; char grade = 'A'; float money = l2.34; bool rich = false; 

cout « "\nStudents love computers"; age = 57; 

Additionally, we have learned how to recognize the data types of literal constants. Single quotes for char, double quotes for string, number without a decimal point for integer, number with a decimal point belongs to the floating-point family, and Boolean can use the reserved words of true or false.

In addition to literal constants, most text books refer to either symbolic constants or named constants but these two refer to the same concept. A symbolic constant is represented by a name similar to how we name variables. Let's say it backwards; the identifier name is the symbol that represents the data item. Within C++ identifier names have some rules. One of the rules says those names should be meaningful. Another rule about using ALL CAPS FOR CONSTANTS is an industry rule. There are two ways to create symbolic or named constants:

#define PI 3.l4l59

Called a defined constant because it uses a textual substitution method controlled by the compiler pre-processor command word "define".

const double PI = 3.l4l59;

The second one is called sometimes called constant variable but that name is contradictory all by itself. How can it be constant and vary at the same time? The better name for the second one is a memory constant because they have a "specific storage location in memory".