Experiment 9: Declarations


Given the ability to construct expressions, it becomes useful to be able to store the value of an expression. That is, if we have an expression whose value is needed several times, it is most time-efficient to evaluate the expression once, store its value, and then access the stored value, rather than spending time reevaluating the expression.

To illustrate, suppose that our problem involves two constant data objects: p and 2p. The inefficient way is to write the value of p and recompute 2p each time they are needed:

   // use 3.14159 and recompute 2.0 * 3.14159 each time it is needed
By contrast, a more efficient approach is to compute and store p and 2p once with a statement called a variable declaration:
   double pi = 3.14159,
          twoPi = 2.0 * pi;
and then use these names each time their values are needed:
   // use pi and twoPi each time they are needed
This has two benefits:

Take a moment and place this declaration in express.cpp. Then modify the output statement to display the values of pi and twoPi, to check the value that has been correctly stored. Continue when this works correctly.

As shown, the names of C++ variable objects consist of whole words, and use lowercase letters, with multiple words being "separated" by capitalizing the first letter in each word after the first one.

A simplified general form of a C++ variable declaration is


   Type IdentifierList ;
where: When execution reaches such a statement, storage is reserved for each identifier in IdentifierList, and each initializer is evaluated and its value placed in the storage associated with its identifier. An uninitialized identifier is described as undefined.

In the space below each description, construct an error-free declaration that matches the description:

sum, containing the integer value zero:




letter, containing the question-mark character:




average, able to hold a real value, but left uninitialized:




done, containing the value false:




Use express.cpp to test their correctness, before continuing.

You should now know how to declare variables in C++. In the next experiment, we'll see another kind of declaration.


Back to the Experiment List

Forward to the Next Experiment


Copyright 1998 by Joel C. Adams. All rights reserved.