The other experiments in this lab have mainly involved variables. In this experiment, we will look at constants. We'll restrict out attention to integer constants to keep things simple, but everything in this experiment applies to real number, character, and string constants — in fact, any type of constant.
Declaring a constant is done in much the same way as declaring a
variable. One difference is that you must use the reserved word
const
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 displays 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 the initialization from one of these declarations 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, which allows us to change the value of our variables as a program executes. This is essential for C++ programs. A constant, however, 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 Experiment #1 for the rule.)
You should also select good names for your constants; for example,
MAX_ALLOWED
, QUARTER3
, and YES
are
much better than A
,Q3
, and YYY
.
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
.