< previous page page_58 next page >

Page 58
Variable
0058-01.gif
Figure 2-2
Variable identifier 
(r)    empNum
Declaring a variable means specifying both its name and its data type. This tells the compiler to associate a name with a memory location whose contents are of a specific type (for example, int, float, or char). The following statement declares empNum to be a variable of type int:
int empNum;
In C++ a variable can contain only data values of the type specified in its declaration. Because of the above declaration, the variable empNum can contain only int values. If the C++ compiler comes across an instruction that tries to store a float value into empNum, it generates extra instructions to convert the float value to an int. In Chapter 3, we examine how these conversions take place.
Here's the syntax template for a variable declaration:
0058-02.gif
where DataType is the name of a data type such as int, float, or char. Notice that a declaration always ends with a semicolon.
From the syntax template, you can see that it is possible to declare several variables in one statement:
int studentCount, maxScore, sumOfScores;
Here, all three variables are declared to be int variables. Our preference, though, is to declare each variable with a separate statement:
int studentCount;
int maxScore;
int sumOfScores;

 
< previous page page_58 next page >