The only problem with our declarations of pi and twoPi in the preceding experiment is that their values are constants (i.e., pi should never change during program execution), and the preceding declaration declares their names as variables -- objects whose values can vary as the program executes.
To illustrate this idea, let's pretend to make a mistake. Place the following assignment statement somewhere after the declaration statement and recompile express.cpp:
pi = -1.1;No error will be generated, because we are simply changing the value of a variable, which is a perfectly valid operation.
To avoid such problems, alter the declaration statement in express.cpp so that it appears as follows:
const double PI = 3.14159,
TWO_PI = 2.0 * PI;
Then alter the assignment and other statements to use the new names:
PI = -1.1;and recompile. Record the error message generated in the space below:
So whenever you have an object in a program whose value should not change, precede its declaration with the keyword const. Then, if you mistakenly try and change its value, the compiler will alert you to your mistake.
By convention, the names of C++ constant objects are whole words, given in all upper-case letters, with underscores used to separate multiple words.
Using this information, construct error-free constant declarations for the identifiers:
SPEED_OF_LIGHT, containing the value 3.0 * 10 to the power 8:
MAXIMUM_SCORE and MINIMUM_SCORE,
containing the integer values 0 and 100, respectively:
MIDDLE_INITIAL, containing the appropriate character for your middle initial:
FOREVER, set to true.
Use express.cpp to verify that your constant declarations are correct.
When they are, proceed.
The type of an expression is the type of value it produces when evaluated. When declaring variables or constants, the type used to declare the identifier should always be the same as the type of value that is to be stored in that identifier's storage.
You should now know how to declare C++ constant objects, and the difference between them and C++ variable objects.
Forward to the Next Experiment