Presentation is loading. Please wait.

Presentation is loading. Please wait.

第八章 敘述層級的控制結構 (Statement-Level Control Structures)

Similar presentations


Presentation on theme: "第八章 敘述層級的控制結構 (Statement-Level Control Structures)"— Presentation transcript:

1 第八章 敘述層級的控制結構 (Statement-Level Control Structures)

2 淡江大學資訊管理系侯永昌 1 Introduction §Levels of Control Flow: 1. Within expressions 2. Among program units 3. Among program statements §Control statement 的多寡影響到: 1. Writability 的增加 2. 降低 language 的 simplicity 3. 增加 compiler 的 size

3 淡江大學資訊管理系侯永昌 2 Introduction §Evolution: l FORTRAN I control statements were based directly on IBM 704 hardware l Much research and argument in the 1960s about the issue l One important result: It was proven that all flowcharts can be coded with only two-way selection and pretest logical loops

4 淡江大學資訊管理系侯永昌 3 Introduction §A control structure is a control statement and the collection of statements whose execution it controls §Overall Design Question: l What control statements should a language have, beyond selection and pretest logical loops?

5 淡江大學資訊管理系侯永昌 4 Compound Statement §Block ︰可以自訂 local variable 的 compound statement §In ALGOL ︰允許 block 和 compound statement begin statement-1;  statement-n; end; §In Pascal ︰不允許 block  In C ︰利用 { … } 來定義 block 和 compound statement

6 淡江大學資訊管理系侯永昌 5 Selection Statements §A selection statement provides the means of choosing between two or more paths of execution §Two general categories: l Two-way selectors l Multiple-way selectors

7 淡江大學資訊管理系侯永昌 6 Two-Way Selection Statements §Design Issues: 1. What is the form and type of the control expression? 2. How are the then and else clauses specified? 3. How should the meaning of nested selectors be specified?

8 淡江大學資訊管理系侯永昌 7 Two-Way Selection Statements  FORTRAN IF: IF (boolean_expr) statement  Problem: can select only a single statement; to select more, a GOTO must be used, as in the following example 例: IF (.NOT. condition) GOTO 20... 20 CONTINUE... §Negative logic is bad for readability

9 淡江大學資訊管理系侯永昌 8 Two-Way Selection Statements §This problem was solved in FORTRAN 77 §Most later languages allow compounds for the selectable segment of their single-way selectors  例: ALGOL 60 if : if (boolean_expr) then statement (the then clause) else statement (the else clause) l The statements could be single or compound

10 淡江大學資訊管理系侯永昌 9 Two-Way Selection Statements §Nested Selectors ︰例如︰ in Java if...... else...  Which if gets the else ?  Java's static semantics rule: else goes with the nearest if

11 淡江大學資訊管理系侯永昌 10 Two-Way Selection Statements  ALGOL 60‘s solution - disallow direct nesting , 利用 compound statement 來避免混淆 if... Then if... then begin begin if... if...then... then... end else... else... end

12 淡江大學資訊管理系侯永昌 11 Two-Way Selection Statements  FORTRAN 90 and Ada’s solution – closing special words if... then if... then...... else end if... else end if... end if end if §Advantage: readability

13 淡江大學資訊管理系侯永昌 12 Multiple-Way Selection Statements §Design Issues: 1. What is the form and type of the control expression? 2. How are the selectable segments specified? 3. Is execution flow through the structure restricted to include just a single selectable segment? 4. What is done about unrepresented expression values?

14 淡江大學資訊管理系侯永昌 13 Multiple-Way Selection Statements  FORTRAN arithmetic IF (a three-way selector)  IF (arithmetic expression) N1, N2, N3 If expression < 0  go to N1 = 0  go to N2 > 0  go to N3

15 淡江大學資訊管理系侯永昌 14 Multiple-Way Selection Statements § 例︰ if (expression) 10, 20, 30 10  go to 40 20  go to 40 30  40  § 大量的使用 go to statement ,對 readability 造成 莫大的傷害︰因為 go to statement 允許你跳到 任何地方去執行,因此整個 IF 結構不能被 encapsulate 在一起,形成一個 unit ,也違反 single entry single exit 的原則

16 淡江大學資訊管理系侯永昌 15 Multiple-Way Selection Statements §Fortran computed go to ︰ Go To (label1, label2, …, labeln), expression  if expression = i  go to labeli if expression is outside 1 ~ n  do nothing, go to next statement §Fortran assign go to ︰ Go To integer-variable (label1, label2, …, labeln)  跳到 integer-variable 所儲存的 label 上

17 淡江大學資訊管理系侯永昌 16 Multiple-Way Selection Statements §Pascal case (from Hoare's contribution to ALGOL W)  case expression of constant_list_1 : statement_1;... constant_list_n : statement_n end §Encapsulated ,而且每一個 condition 結束以後 會自動跳到 end 的下一個 statement 繼續執行

18 淡江大學資訊管理系侯永昌 17 Multiple-Way Selection Statements §Design choices: 1. Expression is any ordinal type ( int, boolean, char, enum ) 2. Segments can be single or compound 3. Only one segment can be executed per execution of the construct 4. 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

19 淡江大學資訊管理系侯永昌 18 Multiple-Way Selection Statements 2. The C, C++, and Java switch switch (expression) { constant_expression_1 : statement_1;... constant_expression_n : statement_n; [ default: statement_n+1] } §Encapsulated ,但是它執完每一個 condition 以後,並不會自動的跳到整個 switch 結構的 下一個 statement ,有 falling through 的特性

20 淡江大學資訊管理系侯永昌 19 Multiple-Way Selection Statements §switch (index) { case 1 : case 3 : odd += 1; sumodd += index; case 2 : case 4 : even += 1; sumeven += index; default : printf (“Error in index = %d\n”, index); § 就算 index = 1 or 3 ,它也會執行 2 與 4 的部份,而 且不論 index 等於多少都會 print 出 error message 。 Switch 有 falling through 的特性,一不小心可能會 造成 reliability 的問題

21 淡江大學資訊管理系侯永昌 20 Multiple-Way Selection Statements §switch (index) { case 1 : case 3 : odd += 1; sumodd += index; break; case 2 : case 4 : even += 1; sumeven += index; break; default : printf (“Error in index = %d\n”, index); §break ︰跳離 switch or loop body

22 淡江大學資訊管理系侯永昌 21 Multiple-Way Selection Statements  Design Choices: (for switch ) 1. Control expression can be only an integer type 2. Selectable segments can be statement sequences, blocks, or compound statements 3. Any number of segments can be executed in one execution of the construct (there is no implicit branch at the end of selectable segments) ︰ To avoid it, the programmer must supply a break statement for each segment , a trade-off between reliability and flexibility (convenience) 4. default clause is for unrepresented values (if there is no default, the whole statement does nothing)

23 淡江大學資訊管理系侯永昌 22 Multiple-Way Selection Statements 3. 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

24 淡江大學資訊管理系侯永昌 23 Multiple-Way Selection Statements §Multiple Selectors can appear as direct extensions to two-way selectors, using else-if clauses § 例如︰ in ALGOL 68, FORTRAN 90, Ada if... then... elsif... then... elsif... then... else... end if

25 淡江大學資訊管理系侯永昌 24 Multiple-Way Selection Statements  Ada’s multiple selectors: Far more readable than deeply nested if ‘s ︰減少 endif 的使用 l Allows a Boolean gate on every selectable group

26 淡江大學資訊管理系侯永昌 25 Iterative Statements §The repeated execution of a statement or compound statement is accomplished either by iteration or recursion ︰可以減少程式的 長度 §Here we look at iteration, because recursion is unit-level control

27 淡江大學資訊管理系侯永昌 26 Iterative Statements §General design issues for iteration control statements: 1. How is iteration controlled? by counting, logical, or a combination 2. Where is the control mechanism in the loop? pretest: at the top of the loop posttest: at the bottom of the loop

28 淡江大學資訊管理系侯永昌 27 Counter-Controlled Loops §Design Issues: 1. What are the type and scope of the loop variable? 2. What is the value of the loop variable at loop termination? 3. Should it be legal for the loop variable or loop parameters to be changed in the loop body, and if so, does the change affect loop control? 4. Should the loop parameters be evaluated only once, or once for every iteration?

29 淡江大學資訊管理系侯永昌 28 Iterative Statements: FORTRAN 90  Syntax: DO label var = start, finish [, stepsize] §Stepsize can be any value but zero §Parameters can be expressions §Design choices: 1. Loop variable must be INTEGER 2. Loop variable always has its last value 3. 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 4. Loop parameters are evaluated only once

30 淡江大學資訊管理系侯永昌 29 Iterative Statements: FORTRAN 90

31 淡江大學資訊管理系侯永昌 30  FORTRAN 90’s Other DO l Syntax: [name:] DO variable = initial, terminal [, stepsize] … END DO [name] Loop variable must be an INTEGER Iterative Statements: FORTRAN 90

32 淡江大學資訊管理系侯永昌 31 Iterative Statements: ALGOL 60  Syntax: for var := do statement where can have: l list of expressions expression step expression until expression expression while boolean_expression  for index := 1 step 2 until 50, 60, 70, 80, index + 1 until 100 do §index = 1, 3, 5, 7,..., 49, 60, 70, 80, 81, 82,..., 100

33 淡江大學資訊管理系侯永昌 32 Iterative Statements: ALGOL 60 §Design choices: 1. Control expression can be int or real ; its scope is whatever it is declared to be 2. Control variable has its last assigned value after loop termination 3. The loop variable cannot be changed in the loop, but the parameters can, and when they are, it affects loop control 4. Parameters are evaluated with every iteration, making it very complex and difficult to read

34 淡江大學資訊管理系侯永昌 33 Iterative Statements: ALGOL 60

35 淡江大學資訊管理系侯永昌 34 Iterative Statements: ALGOL 60

36 淡江大學資訊管理系侯永昌 35 Iterative Statements: Pascal §Syntax: for variable := initial ( to | downto ) final do statement §Design Choices: 1. Loop variable must be an ordinal type of usual scope 2. After normal termination, loop variable is undefined 3. The loop variable cannot be changed in the loop; the loop parameters can be changed, but they are evaluated just once, so it does not affect loop control 4. Loop parameters are evaluated only once

37 淡江大學資訊管理系侯永昌 36 Iterative Statements: Ada  Syntax: for var in [reverse] discrete_range loop... end loop §Design choices: 1. Type of the loop variable is that of the discrete range; its scope is the loop body (it is implicitly declared) 2. The loop variable does not exist outside the loop 3. The loop variable cannot be changed in the loop, but the discrete range can; it does not affect loop control 4. The discrete range is evaluated just once

38 淡江大學資訊管理系侯永昌 37 Iterative Statements: Ada

39 淡江大學資訊管理系侯永昌 38 Iterative Statements: C  Syntax: for ([expr_1] ; [expr_2] ; [expr_3]) statement l The expressions can be whole statements, or even statement sequences, with the statements separated by commas l The value of a multiple-statement expression is the value of the last statement in the expression l If the second expression is absent, it is an infinite loop  例︰ for (i = 0, j = 10; j == i; i++) …

40 淡江大學資訊管理系侯永昌 39 Iterative Statements: 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

41 淡江大學資訊管理系侯永昌 40 Iterative Statements: C

42 淡江大學資訊管理系侯永昌 41 Iterative Statements §C++ Differs from C in two ways: 1. The control expression can also be Boolean 2. The initial expression can include variable definitions (scope is from the definition to the end of the loop body) §Java Differs from C++ in that the control expression must be Boolean

43 淡江大學資訊管理系侯永昌 42 Logically-Controlled Loops §Design Issues: 1. Pretest or posttest? 2. Should this be a special case of the counting loop statement (or a separate statement)?

44 淡江大學資訊管理系侯永昌 43 Logically-Controlled Loops 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

45 淡江大學資訊管理系侯永昌 44 Logically-Controlled Loops 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

46 淡江大學資訊管理系侯永昌 45 Logically-Controlled Loops

47 淡江大學資訊管理系侯永昌 46 User-Located Loop § 由 user 自行決定如何離開 loop §Design issues: 1. Should the conditional be part of the exit? 2. Should control be transferable out of more than one loop?

48 淡江大學資訊管理系侯永昌 47 User-Located Loop : Module-2 §EXIT : unconditional 跳離 loop § 例: loop  sum := sum + index IF sum >= 1000 THEN EXIT END  END

49 淡江大學資訊管理系侯永昌 48 User-Located Loop: Ada §Conditional or unconditional; for any loop; any number of levels Loop1: LOOP1: while... loop while... loop...... Loop2: LOOP2: for... loop for... loop...... exit when.. exit LOOP1 when........ end loop LOOP2; end loop LOOP2;...... end loop LOOP1; end loop LOOP1;

50 淡江大學資訊管理系侯永昌 49 User-Located Loop: Ada §exit loop1 when 是跳到 loop1 以後的第一個 statement §exit when 是跳離最內圈的 loop ,也就是跳到 loop2 以後的第一個 statement §exit 通常用在 unusual / error condition §Syntax: exit [loop name] [when condition]

51 淡江大學資訊管理系侯永昌 50 User-Located Loop: C C, C++, and Java - break  Unconditional; for any loop or switch ; one level only (except Java’s can have a label) ︰ break 和 exit 一樣,都是跳到最內層 loop 以 後的第一個 statement  There is also a continue statement for loops; it skips the remainder of this iteration, but does not exit the loop ,跳到最內層 loop 的最後一個 statement ,並沒有跳離 loop

52 淡江大學資訊管理系侯永昌 51 User-Located Loop: C §while (sum < 1000) { getnext (value); if (value < 0) continue; sum += value; } §while (sum < 1000) { getnext (value); if (value < 0) break; sum += value; }

53 淡江大學資訊管理系侯永昌 52 User-Located Loop: FORTRAN 90  FORTRAN 90 - EXIT l Unconditional; for any loop, any number of levels FORTRAN 90 also has CYCLE, which has the same semantics as C's continue

54 淡江大學資訊管理系侯永昌 53 Iterative Statements §Iteration Based on Data Structures l Concept: use order and number of elements of some data structure to control iteration l 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 例: for (p = hdr; p; p = next(p)) {... }

55 淡江大學資訊管理系侯永昌 54 Iterative Statements §Perl has a built-in iterator for arrays and hashes § 例: foreach $name (@names){ print $name }

56 淡江大學資訊管理系侯永昌 55 Unconditional Branching: go to § 優點: l Flexibility l Powerful: change the flow of execution § 缺點:毫無節制的使用 go to statement 會使 程式變的 difficult to read, maintain  reduce reliability §Some languages do not have them: e.g., Java §Loop exit statements are restricted and somewhat camouflaged goto statements

57 淡江大學資訊管理系侯永昌 56 Unconditional Branching §Label forms: 1. Unsigned int constants: Pascal (with colon) FORTRAN (no colon) 2. Identifiers with colons: ALGOL 60, C 3. Identifiers in >: Ada 4. Variables as labels: PL/I l Can be assigned values and passed as parameters l Highly flexible ,在 run-time 時才決定 goto 到哪裡, but make programs impossible to read and difficult to implement

58 淡江大學資訊管理系侯永昌 57 Restriction on Branch § 可以跳到包含該 goto statement 的 compound statement 中 § 可以跳到包含這個 compound statement 的最 外面一層的 compound statement 中 § 可以跳到包含這個 procedure 的最外面一層 的 procedure 中, goto statement 可以 terminate 一些 procedure 的執行

59 淡江大學資訊管理系侯永昌 58 § 例: while... do begin  while... do begin  100...  end; while... do begin  goto 100;  end; end Restriction on Branch § 例: while... do begin  100...  while... do begin  goto 100;  end; end legal illegal

60 淡江大學資訊管理系侯永昌 59 Guarded Commands §Dijkstra, 1975 §Purpose: to support a new programming methodology (verification during program development)

61 淡江大學資訊管理系侯永昌 60 Guarded Commands 1. Selection: if -> [] ->... [] -> fi §Semantics: when this construct is reached, l Evaluate all boolean expressions l If more than one are true, choose one nondeterministically (randomly) l If none are true, it is a runtime error

62 淡江大學資訊管理系侯永昌 61 Guarded Commands

63 淡江大學資訊管理系侯永昌 62 Guarded Commands 2. Loops do -> [] ->... [] -> od §Semantics: For each iteration: l Evaluate all boolean expressions l If more than one are true, choose one nondeterministically; then start loop again l If none are true, exit loop

64 淡江大學資訊管理系侯永昌 63 Guarded Commands

65 淡江大學資訊管理系侯永昌 64 Guarded Commands § 例: find max if x >= y -> max := x [] y >= x -> max := y fi § 例: sorting do q1 > q2 -> temp := q1; q1 := q2; q2 := temp [] q2 > q3 -> temp := q2; q2 := q3; q3 := temp [] q3 > q4 -> temp := q3; q3 := q4; q4 := temp od

66 淡江大學資訊管理系侯永昌 65 Guarded Commands §Connection between control statements and program verification is intimate §Verification is impossible with gotos §Verification is possible with only selection and logical pretest loops §Verification is relatively simple with only guarded commands

67 淡江大學資訊管理系侯永昌 66 Conclusion §Choice of control statements beyond selection and logical pretest loops is a trade-off between language size and writability § 理論上, language 只需要 sequence, selection 和 pretest logical loop 這三種 control structure 即已足夠,但是 goto statement 對於 exit loop 有其正面的價值 § 如果有更多的 control structure 可以增加 writability ,但是也增加了語言的複雜度 § 盡量少用 goto statement


Download ppt "第八章 敘述層級的控制結構 (Statement-Level Control Structures)"

Similar presentations


Ads by Google