Sams Teach Yourself C++ in 21 Days

(singke) #1
Working with Variables and Constants 51

3


You can combine the steps of creating a variable and assigning a value to it. For exam-
ple, you can combine these two steps for the widthvariable by writing:
unsigned short width = 5;
This initialization looks very much like the earlier assignment, and when using integer
variables like width, the difference is minor. Later, when constis covered, you will see
that some variables must be initialized because they cannot be assigned a value at a later
time.
Just as you can define more than one variable at a time, you can initialize more than one
variable at creation. For example, the following creates two variables of type longand
initializes them:
long width = 5, length = 7;
This example initializes the longinteger variable widthto the value 5 and the longinte-
ger variable lengthto the value 7. You can even mix definitions and initializations:
int myAge = 39, yourAge, hisAge = 40;
This example creates three type intvariables, and it initializes the first (myAge) and third
(hisAge).
Listing 3.2 shows a complete program, ready to compile, that computes the area of a rec-
tangle and writes the answer to the screen.

LISTING3.2 A Demonstration of the Use of Variables


1: // Demonstration of variables
2: #include <iostream>
3:
4: int main()
5: {
6: using std::cout;
7: using std::endl;
8:
9: unsigned short int Width = 5, Length;
10: Length = 10;
11:
12: // create an unsigned short and initialize with result
13: // of multiplying Width by Length
14: unsigned short int Area = (Width * Length);

longis a shorthand version of long int, and shortis a shorthand version of
short int.

NOTE

Free download pdf