Types of Constants in C++
A constant value in C++ is an explicit number or character (such as 1, 0.5, or ‘c’) that doesn’t change. As with variables, every constant has a type. In an expression such as n = 1; the constant value 1 is an int. To make 1 a long integer, write the statement as n = 1L;.
The analogy is as follows: 1 represents a pickup truck with one ball in it, whereas 1L is a dump truck also with one ball. The number of balls is the same in both cases, but the capacity of one of the containers is much larger.
Following the int to long comparison, 1.0 represents the value 1 but in a floating-point container. Notice, however, that the default for floating-point constants is double. Thus, 1.0 is a double number and not a float.
You can use either uppercase or lowercase letters for your special constants. Thus, 10UL and 10ul are both unsigned long integers.
The constant values true and false are of type bool. In keeping with C++’s attention to case, true is a constant but TRUE has no meaning.
A variable can be declared constant when it is created via the keyword const:
const double PI = 3.14159; // declare a constant variable
A const variable must be initialized with a value when it is declared, and its value cannot be changed by any future statement.
Variables declared const don’t have to be named with all capitals, but by convention they often are. This is just a hint to the reader that this so-called variable is, in fact, not.
It may seem odd to declare a variable and then say that it can’t change. Why bother? Largely because carefully named const variables can make a program a lot easier to understand. Consider the following two equivalent expressions:
double dC = 6.28318 * dR; // what does this mean? double dCircumference = TWO_PI * dRadius; // this is a // lot easier to understand
It should be a lot clearer to the reader of this code that the second expression is multiplying the radius of something by 2lcpi to calculate the circumference.