Sams Teach Yourself C++ in 21 Days

(singke) #1
More on Program Flow 205

7


Summary ..............................................................................................................


Today’s lesson started with a look at the gotocommand that you were told to avoid
using. You were then shown different methods to cause a C++ program to loop that don’t
require a goto.
The whilestatement loops check a condition, and if it is true, execute the statements in
the body of the loop. do...whileloops execute the body of the loop and then test the
condition. forloops initialize a value, then test an expression. If the expression is true,
the body of the loop is executed. The final expression in the forheader is then executed
and the condition is then checked again. This process of checking the condition, execut-
ing the statements in the body, and executing the final expression in the forstatement
continues until the conditional expression evaluates to false.
You also learned about continue, which causes while,do...while, and forloops to
start over, and break, which causes while,do...while,for, and switchstatements
to end.

Q&A ....................................................................................................................


Q How do I choose between if...elseand switch?
A If more than just one or two elseclauses are used, and all are testing the same
value, consider using a switchstatement.
Q How do I choose between whileand do...while?
A If the body of the loop should always execute at least once, consider a do...while
loop; otherwise, try to use the whileloop.
Q How do I choose between whileand for?
A If you are initializing a counting variable, testing that variable, and incrementing it
each time through the loop, consider the forloop. If your variable is already ini-
tialized and is not incremented on each loop, a whileloop might be the better
choice. Experienced programmers look for this usage and will find your program
harder to understand if you violate this expectation.
Q Is it better to use while (true)or for (;;)?
A No significant difference exists; however, it is best to avoid both.
Q Why shouldn’t a variable be used as a condition, such as while(n)?
A In the current C++ standard, an expression is evaluated to a Boolean value of true
or false. Although you can equate falseto 0 and trueto any other value, it is
Free download pdf