|
|
|
|
|
|
|
A symbolic constant is a constant that is represented by a name, just as a variable is. 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 there were 15 students per class: |
|
|
|
|
|
|
|
|
* indicates multiplication. |
|
|
|
|
|
|
|
|
|
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. |
|
|
|
|
|
|
|
|
Defining Constants with #define |
|
|
|
|
|
|
|
|
To define a constant the old-fashioned, evil, politically incorrect way, you would enter: |
|
|
|
|
|
|
|
|
#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 15 in the text. |
|
|
|
|
|
|
|
|
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, there is a new, better, less fattening, and more tasteful way 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. |
|
|
|
|
|