The other experiments in this lab have you play around with variables. We'll look at constants in this experiment. We'll play around with integer constants to keep things simple, but everything in this experiment applies to real-number, character, and string constants---in fact, any type of a constant.
Declaring a constant is done mostly the same way as declaring a
variable. One difference is that you must use the const
reserved word before the declaration; the second difference is that
you must initialize a constant. A third difference is that our
naming conventions change, and we'll use all capital letters for the
identifiers.
Declare two new integer variables in your program named CONST1
and CONST2
. Initialize them to anything you like,
but make sure they're both initialized to something. Add an
output statement that prints their values.
Compile and execute your program. Make sure your program displays the right information; keep debugging until it does.
Question #2.6.1: What are the two statements (a declaration and an output statement) that you've added to your program?
Now turn these new variables into constants by adding the word const
before the int
keyword. Compile and execute the
program.
Question #2.6.2: How has the output changed?
So what's the point? Remove one of the initializations, and try to compile your code.
Question #2.6.3: What is the first error message that your compiler gives you?
So you have to initialize a constant. But then why don't we use constants all the time? We're supposed to initialize our variables anyway, so why not have the compiler enforce it?
In the next lab, we'll look at the assignment operator. The assignment operator allows us to change the value of our variables as the programs execute. This is essential for C++ programs. A constant, though, cannot be assigned a value after it has been initialized. We will explore this in the next lab.
Constants are named using identifiers and follow the same rule as the rule for variables. (See the Experiment #1 for the rule.)
You also want to pick good names for your constants. A
,
Q3
, and YYY
are bad. MAX_ALLOWED
, QUARTER3
, and YES
are much better. The identifier should
reflect the purpose and function of the constant value that it
holds.
But, as you might note, the convention for identifiers for constants is slightly different:
MAX_ALLOWED
instead of MAXALLOWED
or MAXaLLOWED
.