Starting a web site - Chapter 5 Control Structures: Part 2 215 Common

Chapter 5 Control Structures: Part 2 215 Common Programming Error 5.7 Forgetting a break statement when one is needed in a switch structure is a logic error. Good Programming Practice 5.11 Provide a default case in switch statements. Cases not explicitly tested in a switch statement without a default case are ignored. Including a default case focuses the programmer on the need to process exceptional conditions. There are situations in which no default processing is needed. Good Programming Practice 5.12 Although the cases and the default case in a switch structure can occur in any order, it is considered a good programming practice to place the default clause last. Good Programming Practice 5.13 In a switch structure, when the default clause is listed last, the break for that case statement is not required. Some programmers include this break for clarity and symmetry with other cases. Note that listing case labels together (such as case1:case2: with no statements between the cases) performs the same set of actions for each case. When using the switch structure, remember that the expression after each casecan be only a constant integral expression (i.e., any combination of character constants and integer constants that evaluates to a constant integer value). A character constant is represented as the specific character in single quotes, such as ‘A’. An integer constant is simply an integer value. The expression after each case also can be a constant variable i.e., a variable that contains a value which does not change for the entire program. Such a variable is declared with keyword final (discussed in Chapter 6). When we discuss object-oriented programming in Chapter 9, we present a more elegant way to implement switch logic. We use a technique called polymorphism to create programs that are often clearer, easier to maintain and easier to extend than programs using switch logic. 5.6 The do/while Repetition Structure The do/whilerepetition structure is similar to the while structure. In the while structure, the program tests the loop-continuation condition at the beginning of the loop, before performing the body of the loop. The do/while structure tests the loop-continuation condition after performing the body of the loop; therefore, the loop body always executes at least once. When a do/while structure terminates, execution continues with the statement after the while clause. Note that it is not necessary to use braces in the do/while structure if there is only one statement in the body. However, most programmers include the braces, to avoid confusion between the while and do/whilestructures. For example, while ( condition ) normally is the first line of a while structure. A do/while structure with no braces around a single-statement body appears as do statement while ( condition ); Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

Leave a Reply