1 / 52

Statement-Level Control Structures

Statement-Level Control Structures. Robert W. Sebesta, Chapter 8. Chapter 8 Topics. Introduction Selection Statements Iterative Statements Unconditional Branching Guarded Commands Conclusions. Control statements, control structures. Control Statements

Download Presentation

Statement-Level Control Structures

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Statement-Level Control Structures Robert W. Sebesta, Chapter 8

  2. Chapter 8 Topics • Introduction • Selection Statements • Iterative Statements • Unconditional Branching • Guarded Commands • Conclusions

  3. Control statements, control structures • Control Statements • Selecting among several alternative control flow paths • Causing the repeated execution of collections of statements • Control Structure • A control statement and the collection of statements whose execution it controls • Categories include: • Compound statements • Selection statements • Iterative statements • Unconditional branching

  4. Compound statements • Allow a collection of statements to be abstracted to a single statement • A block is a compound statement which includes data declarations • Some languages have specially delimited(限定)compound statements: begin…end { … } • Some control constructs have built-in(嵌入)delimiters(定義符號): repeat…until compound statement 複合敘述 在程式設計語言中,由相鄰敘述組成的一種敘述。通常,敘述被用某些語法規則組合在一起。敘述體含有一個或多個其它敘述的敘述。

  5. Selection statements • Provide a means of choosing between 2 or more execution paths • Two general categories: • Two-way selectors • N-way selectors (or Multiple-way)

  6. 2-way selection statements • General form:If control_expression then clause Else clause • Design issues: • What is the form and type of expression that controls the expression? • Can a single statement, a sequence of statements, or a compound statement be selected? • How are the then and else cluses specified? • How should the meaning of nested selectors be specified?

  7. 2-way selection statements • FORTRAN IV’s logical if has the form IF (Boolean expr) statement • Example: IF (X .GT. 10) GOTO 20 SUM = SUM + X X = X + 1 20 CONTINUE

  8. 2-way selection statements • ALGOL 60 2-way selector: if (Boolean_expr) thenstatementelsestatement • Nested if-else • Special delimiters and selection closure • ALGOL 68, FORTRAN 77, Ada use end if

  9. 2-Way Selection Statements • ALGOL 60's solution - disallow direct nesting if ... then if ... then beginbegin if ... if ... then ... end else ... else ... end

  10. 2-Way Selection Statements • Nested Selectors • e.g. (Java) if (sum == 0) if (count == 0) result = 0; else result = 1; • Which if gets the else? • Java's static semantics rule: else goes with the nearest if

  11. 2-Way Selection Statements • Put inner if-then in a compound • e.g. (Java) if (sum == 0){ if (count == 0) result = 0;} else result = 1; • C, C++, and C# have the same problem as Java with selection statement nesting.

  12. 2-Way Selection Statements • FORTRAN 90 and Ada solution –closing special words • e.g. (Ada) if ... then if ... then if ... then if ... then ... ... else end if ... else end if ... end if end if • Advantage: readability

  13. Multiple selection statements • Design issues: • What is the form and type of expression that controls the selection • May single statements, sequences of statements, or compound statements be selected • Is the entire construct encapsulated(封裝)in a syntactic structure • Is execution flow through the structure restricted to include just a single selectable segment • How should unrepresented selector expression values be handled

  14. Multiple selection statements • Design choices: • Expression is any ordinal type (int, boolean, char, enum) • Segments can be single or compound • Only one segment can be executed per execution of the construct • In Wirth's Pascal, result of an unrepresented control expression value is undefined (In 1984 ISO Standard, it is a runtime error) • Many dialects now have otherwise or else clause

  15. Modern multiple selectors • C, C++, Java switch statement • FORTRAN arithmetic IF • Ada case statement • Pascal case statement

  16. Multiple selection statements • C multiple selector construct, switch Switch (expression) { case constant_expression_1: statement_1;… case constant_expression_n: statement_n; [default: statement_n + 1]} See Page 325~327

  17. C, C++, Java switch statement switch (expression) {case constant_expression_1:statement_1; …case constant_expression_n:statement_n; [default: statement_n+1] } Switch (index) { case 1: case 3: odd += 1; sumodd += index; break; case 2: case 4: even += 1; sumeven += index; break; default: printf(“Error in switch, index = %d\n”, index); }

  18. Multiple selection statements • Design Choices: (for switch) • Control expression can be only an integer type • Selectable segments can be statement sequences, blocks, or compound statements • Any number of segments can be executed in one execution of the construct (there is no implicit branch at the end of selectable segments) • (a trade-off between reliability and flexibility--convenience) • To avoid it, the programmer must supply a break statement for each segment • default clause is for unrepresented values (if there is no default, the whole statement does nothing)

  19. Multiple selection statements • FORTRAN arithmetic IF: IF (arith_expr) N1, N2, N3 • Example: IF (expression) 10, 20, 3010 … … GO TO 4020 … … GO TO 4030 … …40 • The arithmetic if can be entered through any of itsstatements from anywhere in the program.

  20. Ada case statement see page 327 • Descendant of the multiple-selector statement that appeared in ALGOL W in 1966 • Ada's case is similar to Pascal's case, except: 1. Constant lists can include: • Subranges e.g., 10..15 • Boolean OR operators e.g., 1..5 | 7 | 15..20 2. Lists of constants must be exhaustive(詳盡的) • Often accomplished with others clause • This makes it more reliable case expression is when choice list => statement_sequence; … when choice list => statement_sequence; [when others => statement_sequence;] end case;

  21. Multiple Selection Using if • Multiple Selectors can appear as direct extensions to two-way selectors, using else-if clauses (ALGOL 68, FORTRAN 90, Ada) Ada: if ... then ... elsif ... then ... elsif ... then ... else ... end if

  22. Multiple Selection Using ifsee page 328 if count < 10 then Bag1 := True; elseif count <100 then Bag2 := True; elseif count <1000 then Bag3 := True; end if; • Ada’s multiple selectors “elseif”: • Far more readable than deeply nested if's • Allows a Boolean gate on every selectable group

  23. Iterative statements • The repeated execution of a statement or compound statement is accomplished either by iteration(重複) or recursion(遞迴) • Design issues: • How is iteration controlled • Where should the control mechanism appear in the loop • Categories: • Counter-controlled loops • Logically-controlled loops • User-located loop control mechanisms • Data structure based-iteration

  24. Counter-controlled loops • Design issues: • A counting iterative control statement has a variable, called the loop variable. • Type and scope of loop variable • Value of loop variable at loop termination • Is it legal for loop variable or parameters to be changed in the loop body, and if so, does the change affect loop control • Are loop parameters evaluated only once, or once for each iteration

  25. Do Statement of Fortran 95 FORTRAN 95 see Page 331~332 • Syntax: DO label variable = initial, terminal [, stepsize] • Stepsize can be any value but zero • Parameters can be expressions • Design choices: • Loop variable must be INTEGER • Loop variable always has its last value • The loop variable cannot be changed in the loop, but the parameters can; because they are evaluated only once, it does not affect loop control • Loop parameters are evaluated only once

  26. Do Statement of Fortran 95 • FORTRAN 95’s Other DO • Syntax: [name:] DO variable = initial, terminal [, stepsize] … END DO [name] • End Do instead of a labeled statement • Loop variable must be an INTEGER

  27. The Ada for Statement Ada • Syntax: for var in [reverse] discrete_range loop ... end loop; Count : Float := 1.35; for Count in 1 .. 10 loop sum := sum + Count; end loop;

  28. The Ada for Statement • Ada Design choices: • Type of the loop variable is that of the discrete range; its scope is the loop body (it is implicitly declared) • The loop variable does not exist outside the loop • The loop variable cannot be changed in the loop, but the discrete range can; it does not affect loop control • The discrete range is evaluated just once

  29. For Statement of C-Based Lang. • Syntax: see page 333 for ([expr_1] ; [expr_2] ; [expr_3]) statement • The expressions can be whole statements, or even statement sequences, with the statements separated by commas • The value of a multiple-statement expression is the value of the last statement in the expression e.g., for (i = 0, j = 10; j == i; i++) … • If the second expression is absent, it is an infinite loop

  30. For Statement of C-Based Lang. • C Design Choices: 1. There is no explicit(明確的)loop variable 2. Irrelevant(不恰當) 3. Everything can be changed in the loop 4. The first expression is evaluated once, but the other two are evaluated with each iteration • This loop statement is the most flexible

  31. For Statement of C-Based Lang. for (count1=0,count2=1.0;count1<=10 && count2<=100.0;sum=++count1+count2, count2 *= 2.5); Count1=0 Count2=1.0 Loop: if count1>10 goto out if count2>100.0 goto out count1 = count1 +1 sum = count1+count2 count2 = count2 * 2.5 goto loop out: …

  32. For Statement of C-Based Lang. C++ • Differs from C in two ways: • The control expression can also be Boolean • The initial expression can include variable definitions (scope is from the definition to the end of the loop body) for (int count=0;count<len;count++){…} Java • Differs from C++ in that the control expression must be Boolean

  33. Logically-controlled loops • Design issues: • Is control pretest or posttest • Should this be a special case of the counting loop statement (or a separate statement)? • Examples • while statement (see page 335) • do while (see page 335) • repeat until

  34. Logically-controlled loops • Language Examples: 1. Pascal has separate pretest and posttest logical loop statements (while-do and repeat-until) 2. C and C++ also have both, but the control expression for the posttest version is treated just like in the pretest case (while - do and do - while) 3 Java is like C, except the control expression must be Boolean (and the body can only be entered at the beginning--Java has no goto

  35. Logically-controlled loops • Language Examples (continued): 4. Ada has a pretest version, but no posttest 5. FORTRAN 77 and 90 have neither 6. Perl has two pretest logical loops, while and until, but no posttest logical loop

  36. User-located loop control • Design issues: • Is conditional mechanism an integral part of exit • Should only one loop body be exited, or can enclosing loops also be exited • Examples: • Ada loop – exit [loop_label] [when condition] • C loops – break and continue

  37. User-located loop control • Examples: Ada - conditional or unconditional; for any loop; any number of levels for ... loop LOOP1: ... while ... loop exit when ... ... ... LOOP2: end loop for ... loop ... exit LOOP1 when .. ... end loop LOOP2; ... end loop LOOP1;

  38. User-located loop control C , C++, and Java –break(Page 337~340) • Unconditional; for any loop or switch; one level only (except Java’s can have a label) • There is also a continue statement for loops; it skips the remainder of this iteration, but does not exit the loop

  39. User-located loop control FORTRAN 90 - EXIT • Unconditional; for any loop, any number of levels • FORTRAN 90 also has CYCLE, which has the same semantics as C's continue

  40. Iteration based on data structures • Use order and number of elements of some data structure to control iteration • Control mechanism is a call to a function that returns the next element in some chosen order, if there is one; else exit loop • C's for can be used to build a user-defined iterator • e.g. for (ptr=root;ptr==null; traverse(ptr)) { ... }(Page 340~1)

  41. Iterative Statements • Perl has a built-in iterator for arrays and hashes e.g., foreach $name (@names) { print $name }

  42. Unconditional Branching - goto • Problem: readability • Some languages do not have them: e.g., Java • Loop exit statements are restricted and somewhat camouflaged(掩飾) goto’s

  43. Unconditional Branching • Label forms: • Unsigned int constants: Pascal (with colon) FORTRAN (no colon) • Identifiers with colons: ALGOL 60, C • Identifiers in << ... >>: Ada • Variables as labels: PL/I • Can be assigned values and passed as parameters • Highly flexible, but make programs impossible to read and difficult to implement

  44. Guarded Commands • Dijkstra, 1975 • Purpose: to support a new programming methodology (verification during program development)

  45. Guarded Commands • Selection:if <boolean> -> <statement> [] <boolean> -> <statement> ... [] <boolean> -> <statement> fi • Semantics: when this construct is reached, • Evaluate all boolean expressions • If more than one are true, choose one nondeterministically(不確定地) • If none are true, it is a runtime error

  46. Guarded Commands • Idea: if the order of evaluation is not important, the program should not specify one

  47. Guarded Commands 2. Loops do <boolean> -> <statement> [] <boolean> -> <statement> ... [] <boolean> -> <statement> od

  48. Guarded Commands • Semantics: For each iteration: • Evaluate all boolean expressions • If more than one are true, choose one nondeterministically; then start loop again • If none are true, exit loop

More Related