Constants
Like variables, constants are data storage locations. Unlike variables, and as the name implies, constants don't change. You must initialize a constant when you create it, and you cannot assign a new value later.
Literal Constants
C++ has two types of constants: literal and symbolic.
A literal constant is a value typed directly into your program wherever it is needed. For example:
int myAge = 39;
myAge is a variable of type int; 39 is a literal constant. You can't assign a value to 39, and its value can't be changed.
Symbolic Constants
A symbolic constant is a constant that is represented by a name, just as a variable is represented. Unlike a variable, however, after a constant is initialized, its value can't be changed.
If your program has one integer variable named students and another named classes, you could compute how many students you have, given a known number of classes, if you knew each class consisted of 15 students:
students = classes * 15;
In this example, 15 is a literal constant. Your code would be easier to read, and easier to maintain, if you substituted a symbolic constant for this value:
students = classes * studentsPerClass
If you later decided to change the number of students in each class, you could do so where you define the constant studentsPerClass without having to make a change every place you used that value.
Two ways exist to declare a symbolic constant in C++. The old, traditional, and now obsolete way is with a preprocessor directive, #define.
Defining Constants with #define
To define a constant the traditional way, you would enter this:
#define studentsPerClass 15
Note that studentsPerClass is of no particular type (int, char, and so on). #define does a simple text substitution. Every time the preprocessor sees the word studentsPerClass, it puts in the text 15.
Because the preprocessor runs before the compiler, your compiler never sees your constant; it sees the number 15.
Defining Constants with const
Although #define works, a new, much better way exists to define constants in C++:
const unsigned short int studentsPerClass = 15;
This example also declares a symbolic constant named studentsPerClass, but this time studentsPerClass is typed as an unsigned short int. This method has several _advantages in making your code easier to maintain and in preventing bugs. The biggest difference is that this constant has a type, and the compiler can enforce that it is used according to its type.
NOTE
Constants cannot be changed while the program is running. If you need to change studentsPerClass, for example, you need to change the code and recompile.
NOTE
DO watch for numbers overrunning the size of the integer and wrapping around incorrect values.
DO give your variables meaningful names that reflect their use.
DON'T use keywords as variable names.