Nesting Loops

Just as if statements and other control structures such as try/catch can be nested within each other, so can loops. However, just as with if statements, this can be a bad idea, and should lead you to consider refactoring the inner loop into a function of its own.

As an example of this, you might create a variant of the UserWantsToContinue() function. This would contain a loop that would only end when the user entered either y or n. No longer could any character other than y be used to mean “continue.” Listing 10.1 shows such a function.

Listing 10.1. UserWantsToContinueYOrN in PromptModule
 1: bool UserWantsToContinueYOrN (const char *theThingWeAreDoing) 2: { 3: char DoneCharacter; 4: *5: do *6: { 7: cout << 8: endl << 9: theThingWeAreDoing ...

Get SAMS Teach Yourself C++ in 10 Minutes SECOND EDITION now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.