Simplifying by Using a bool Variable

The big danger in the earlier example is that, because you've put the same bool expression in two places, you will cause an accident if you do not make or keep the two expressions identical. This could lead to a serious and hard-to-solve problem in your program during repair or enhancement. You can use a bool variable to avoid it, as shown in Listing 10.3.

Listing 10.3. UserWantsToContinueYOrN in PromptModule with a bool Expression
  1:    bool UserWantsToContinueYOrN (const char *theThingWeAreDoing)
  2:    {
  3:       char DoneCharacter;
 *4:       bool InvalidCharacterWasEntered = false;
  5:
  6:       do
  7:       {
  8:          cout <<
  9:             endl <<
 10:             theThingWeAreDoing <<
 11:             " - Press "n" and "Enter" to stop: ";
 12:
 13:          cin >> DoneCharacter;
 14:
*15:          InvalidCharacterWasEntered =
*16:             !
*17:             (
*18:                (DoneCharacter == 'y')
*19:                ||
*20:                (DoneCharacter == 'n')
*21:             );
 22:
*23:          if (InvalidCharacterWasEntered)
 24:          {
 25:              cout << ".Error – " << "please enter "y" or "n"." << endl;
 26:          };
 27:       }
*28:       while (InvalidCharacterWasEntered);
 29:
 30:       return (DoneCharacter != 'n'),
 31:    }

Let's start with line 4, which defines a bool variable for the purpose of saving the result of the bool expression. Your first reaction might be to wonder why this variable, which is to be used as the loop condition, is defined outside the loop.


An important rule of C++ is that a variable declared inside a block (remember, a block is a set of lines surrounded by braces) is created when the control flow reaches the opening brace, and disappears when control flows past the closing brace. If you put your bool variable inside the loop, while cannot use it in the condition, and the result is a compiler message that looks like this:

[C++ Error] PromptModule.cpp(34): E2451 Undefined symbol 'InvalidCharacterWasEntered'

Next, the bool expression has been moved out of the if condition and onto lines 15–21, which assign the result to the variable.

In line 23, the if statement tests the variable to see whether there is a problem and therefore a need to produce the error message.

Line 28 uses the same variable to decide whether the loop needs to repeat, prompting the user again.

This is much safer than using two identical expressions, of course. And you've given a name to the expression, so it's much easier to understand what it is intended to represent.

Don't forget to add the prototype to the header and modify main.cpp to use this new and improved function. And, of course, don't forget regression testing.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.29.48