150 likes | 166 Vues
Statements: Control Structure Issues (Chapters 15-17 and 19 of Code Complete ). Don Bagert CSSE 375, Rose-Hulman October 17, 2006. Outline. Selection Statements Loops Some Other Statements. Selection Statements. Definition.
E N D
Statements:Control Structure Issues(Chapters 15-17 and 19 of Code Complete) Don Bagert CSSE 375, Rose-Hulman October 17, 2006
Outline • Selection Statements • Loops • Some Other Statements
Definition • A selection statement is a statement where a selection of which statements to execute out of two or more possibilities is determined through the use of a condition of some kind. • Examples: if and switch statements in Java and C++
Some Selection Statement Issues – 1/3 • In general, case (switch) statements should be used whenever possible if three of more cases are involved. • However, in most languages, case statements are limited to the comparison of an “integral” variable to a series of values or value ranges, so a nested if-then-else must often be used The Boston rail yard: A view of multiple train switches.
Some Selection Statement Issues – 2/3 • In a nested if-then-else, “lining up” all of the elses aids readability. • Example (in Java): if (NumberInput == 0) NumberOfZeroesCounted++; else if (NumberInput > 0) NumberOfPositivesCounted++; else NumberOfNegativesCounted++;
Some Selection Statement Issues – 3/3 • Using an “else do nothing” can be useful, especially with nested if statements. • Example (using an outline in PDL syntax): if ... then if ... then ... else ... • With which then will the else be associated?
Some Loop Issues – 1/3 • A pre-test loop (such as the while statement in Java) is most generic of the loop statements, since it can be used to represent any loop. • However, if the loop definitely needs to be executed at least once (e.g. in a bubblesort) a post-test loop (such as the do-while in Java) should be used instead.
Some Loop Issues – 2/3 • When for loops should be used varies from language to language • Visual Basic Example (a simple format): for ListIndex = 1 to ListSize • Java and C++ Example (more complex): for (i = 0; i < ListSize && !found; i++)
Some Loop Issues – 3/3 • Entry from the beginning of and exit from either the beginning or the end of the loop is useful in many ways • Therefore (in my opinion), the use of features such as the “break” in Java should be avoided if at all possible
Goto and Return Statements • The goto is a very powerful statement which you will probably find in frequent use in certain types of legacy code • The return statement has some features of the goto. In my opinion, it should generally not be used for procedures (void functions in Java and C++) and only as the last statement of a function. • Example: Return (FunctionValue);
Recursion • Recursion should be used only when the complexity is significantly less than that of using a loop • Infinite recursion must be avoided in the same way as infinite loops are