|
|
|
|
|
|
|
With this form it is easier, when modifying a program, to add new variables to the list or delete ones you no longer want. |
|
|
|
|
|
|
|
|
Declaring each variable with a separate statement also allows you to attach comments to the right of each declaration, as we do in the Payroll program: |
|
|
|
|
|
|
|
|
float payRate; // Employee's pay rate
float hours; // Hours worked
float wages; // Wages earned
float total; // Total company payroll
int empNum; // Employee ID number |
|
|
|
|
|
|
|
|
These declarations tell the compiler to set up locations in memory for four float variablespayRate, hours, wages, and totaland to set up one location for an int variable named empNum The comments explain to the reader what each variable represents. |
|
|
|
|
|
|
|
|
Now that we've seen how to declare variables in C++, let's look at how to declare constants. |
|
|
|
|
|
|
|
|
All numbersinteger and floating pointare constants. So are single characters (enclosed in single quotes) and sequences of characters, orstrings (enclosed in double quotes). |
|
|
|
|
|
|
|
|
In C++ as in mathematics, a constant is something whose value never changes. |
|
|
|
|
|
|
|
|
We use numeric constants as part of arithmetic expressions (as you will see later in this chapter). For example, we can write a statement that adds the constants 5 and 6 and places the result into a variable named sum. When we use the actual value of a constant in a program, we are using a literal value (or literal). |
|
|
|
 |
|
 |
|
|
Literal Value Any constant value written in a program. |
|
|
|
|
|
|
|
|
Notice that achar literal can have only one character within single quotes ('), whereas a string literal can have many characters and must be enclosed within double quotes ("). The use of quotes lets us differentiate between char or string literals and identifiers. amount (in double quotes) is the character string made up of the letters a, m, o, u, n, and t in that order. On the other hand, amount (without the quotes) is an identifier, perhaps the name of a variable. |
|
|
|
|
|