StatementLevel Control Structures Introduction Levels of Control Flow

  • Slides: 67
Download presentation
第八章 敘述層級的控制結構 (Statement-Level Control Structures)

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

Introduction § Levels of Control Flow: 1. Within expressions 2. Among program units 3.

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 淡江大學資訊管理系侯永昌 1

Introduction § Evolution: l FORTRAN I control statements were based directly on IBM 704

Introduction § Evolution: l FORTRAN I control statements were based directly on IBM 704 hardware l Much research and argument in the 1960 s 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 淡江大學資訊管理系侯永昌 2

Introduction § A control structure is a control statement and the collection of statements

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? 淡江大學資訊管理系侯永昌 3

Compound Statement § Block︰可以自訂local variable的compound statement § In ALGOL︰允許block和compound statement begin statement-1; statement-n; end;

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 淡江大學資訊管理系侯永昌 4

Selection Statements § A selection statement provides the means of choosing between two or

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

Two-Way Selection Statements § Design Issues: 1. What is the form and type of

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

Two-Way Selection Statements § FORTRAN IF: IF (boolean_expr) statement § Problem: can select only

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

Two-Way Selection Statements § This problem was solved in FORTRAN 77 § Most later

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 淡江大學資訊管理系侯永昌 8

Two-Way Selection Statements § Nested Selectors︰例如︰in Java if. . . else. . . §

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 淡江大學資訊管理系侯永昌 9

Two-Way Selection Statements § ALGOL 60‘s solution - disallow direct nesting, 利用compound statement來避免混淆 if.

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

Two-Way Selection Statements § FORTRAN 90 and Ada’s solution – closing special words if.

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

Multiple-Way Selection Statements § Design Issues: 1. What is the form and type of

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 淡江大學資訊管理系侯永昌 12 expression values?

Multiple-Way Selection Statements § FORTRAN arithmetic IF (a three-way selector) § IF (arithmetic expression)

Multiple-Way Selection Statements § FORTRAN arithmetic IF (a three-way selector) § IF (arithmetic expression) N 1, N 2, N 3 If expression < 0 go to N 1 = 0 go to N 2 > 0 go to N 3 淡江大學資訊管理系侯永昌 13

Multiple-Way Selection Statements § 例︰if (expression) 10, 20, 30 10 go to 40 20

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的原則 淡江大學資訊管理系侯永昌 14

Multiple-Way Selection Statements § Fortran computed go to︰ Go To (label 1, label 2,

Multiple-Way Selection Statements § Fortran computed go to︰ Go To (label 1, label 2, …, 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 (label 1, label 2, …, labeln) 跳到integer-variable所儲存的label上 淡江大學資訊管理系侯永昌 15

Multiple-Way Selection Statements § Pascal case (from Hoare's contribution to ALGOL W) § case

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繼續執行 淡江大學資訊管理系侯永昌 16

Multiple-Way Selection Statements § Design choices: 1. Expression is any ordinal type (int, boolean,

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) l Many dialects now have otherwise or else clause 淡江大學資訊管理系侯永昌 17

Multiple-Way Selection Statements 2. The C, C++, and Java switch (expression) { constant_expression_1 :

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

Multiple-Way Selection Statements § switch (index) { case 1 : case 3 : odd

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 = %dn”, index); § 就算index = 1 or 3,它也會執行2與4的部份,而 且不論index等於多少都會print出error message。 Switch有falling through的特性,一不小心可能會 造成reliability的問題 淡江大學資訊管理系侯永昌 19

Multiple-Way Selection Statements § switch (index) { case 1 : case 3 : odd

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 = %dn”, index); § break︰跳離switch or loop body 淡江大學資訊管理系侯永昌 20

Multiple-Way Selection Statements § Design Choices: (for switch) 1. Control expression can be only

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) 淡江大學資訊管理系侯永昌 21

Multiple-Way Selection Statements 3. Ada's case is similar to Pascal's case, except ︰ 1.

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 淡江大學資訊管理系侯永昌 22

Multiple-Way Selection Statements § Multiple Selectors can appear as direct extensions to two-way selectors,

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. . . else. . . end if 淡江大學資訊管理系侯永昌 23

Multiple-Way Selection Statements § Ada’s multiple selectors: l Far more readable than deeply nested

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

Iterative Statements § The repeated execution of a statement or compound statement is accomplished

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 淡江大學資訊管理系侯永昌 25

Iterative Statements § General design issues for iteration control statements: 1. How is iteration

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 淡江大學資訊管理系侯永昌 26

Counter-Controlled Loops § Design Issues: 1. What are the type and scope of the

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? 淡江大學資訊管理系侯永昌 27

Iterative Statements: FORTRAN 90 § § Syntax: DO label var = start, finish [,

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 淡江大學資訊管理系侯永昌 28

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

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

Iterative Statements: FORTRAN 90 § FORTRAN 90’s Other DO l Syntax: [name: ] DO

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

Iterative Statements: ALGOL 60 § Syntax: for var : = <list_of_stuff> do statement where

Iterative Statements: ALGOL 60 § Syntax: for var : = <list_of_stuff> do statement where <list_of_stuff> can have: l list of expressions l expression step expression until 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, 81, 82, . . . , 100 淡江大學資訊管理系侯永昌 31

Iterative Statements: ALGOL 60 § Design choices: 1. Control expression can be int or

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 淡江大學資訊管理系侯永昌 32

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

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

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

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

Iterative Statements: Pascal § Syntax: for variable : = initial (to | downto) final

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 淡江大學資訊管理系侯永昌 35

Iterative Statements: Ada § Syntax: for var in [reverse] discrete_range loop. . . end

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 淡江大學資訊管理系侯永昌 36

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

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

Iterative Statements: C § Syntax: for ([expr_1] ; [expr_2] ; [expr_3]) statement l The

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++) … 淡江大學資訊管理系侯永昌 38

Iterative Statements: C § Design Choices: 1. There is no explicit loop variable 2.

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

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

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

Iterative Statements § C++ Differs from C in two ways: 1. The control expression

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 淡江大學資訊管理系侯永昌 41

Logically-Controlled Loops § Design Issues: 1. Pretest or posttest? 2. Should this be a

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)? 淡江大學資訊管理系侯永昌 42

Logically-Controlled Loops 1. Pascal has separate pretest and posttest logical loop statements (while-do and

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

Logically-Controlled Loops 4. Ada has a pretest version, but no posttest 5. FORTRAN 77

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

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

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

User-Located Loop § 由user自行決定如何離開loop § Design issues: 1. Should the conditional be part of

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? 淡江大學資訊管理系侯永昌 46

User-Located Loop:Module-2 § EXIT:unconditional跳離loop § 例: loop sum : = sum + index IF

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

User-Located Loop: Ada § Conditional or unconditional; for any loop; any number of levels

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

User-Located Loop: Ada § exit loop 1 when是跳到loop 1以後的第一個 statement § exit when是跳離最內圈的loop,也就是跳到 loop

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

User-Located Loop: C C , C++, and Java - break § Unconditional; for any

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 淡江大學資訊管理系侯永昌 50

User-Located Loop: C § while (sum < 1000) { getnext (value); if (value <

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; } 淡江大學資訊管理系侯永昌 51

User-Located Loop: FORTRAN 90 § FORTRAN 90 - EXIT l l Unconditional; for any

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

Iterative Statements § Iteration Based on Data Structures l l Concept: use order and

Iterative Statements § Iteration Based on Data Structures l l Concept: 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 例: for (p = hdr; p; p = next(p)) {. . . } 淡江大學資訊管理系侯永昌 53

Iterative Statements § Perl has a built-in iterator for arrays and hashes § 例:

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

Unconditional Branching: go to § 優點: l Flexibility l Powerful: change the flow of

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 淡江大學資訊管理系侯永昌 55

Unconditional Branching § Label forms: 1. Unsigned int constants: Pascal (with colon) FORTRAN (no

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 l Can be assigned values and passed as parameters Highly flexible,在run-time時才決定goto到哪裡, but make programs impossible to read and difficult to implement 淡江大學資訊管理系侯永昌 56

Restriction on Branch § 可以跳到包含該goto statement的compound statement中 § 可以跳到包含這個compound statement的最 外面一層的compound statement中 § 可以跳到包含這個procedure的最外面一層

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

Restriction on Branch § 例: while. . . do begin while. . . do

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

Guarded Commands § Dijkstra, 1975 § Purpose: to support a new programming methodology (verification

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

Guarded Commands 1. Selection: if <boolean> -> <statement> []<boolean> -> <statement>. . . []

Guarded Commands 1. Selection: if <boolean> -> <statement> []<boolean> -> <statement>. . . [] <boolean> -> <statement> 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 淡江大學資訊管理系侯永昌 60

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

Guarded Commands 2. Loops do <boolean> -> <statement> [] <boolean> -> <statement>. . . [] <boolean> -> <statement> 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 淡江大學資訊管理系侯永昌 62

Guarded Commands § 例:find max if x >= y -> max : = x

Guarded Commands § 例:find max if x >= y -> max : = x [] y >= x -> max : = y fi § 例:sorting do q 1 > q 2 -> temp : = q 1; q 1 : = q 2; q 2 : = temp [] q 2 > q 3 -> temp : = q 2; q 2 : = q 3; q 3 : = temp [] q 3 > q 4 -> temp : = q 3; q 3 : = q 4; q 4 : = temp od 淡江大學資訊管理系侯永昌 64

Guarded Commands § Connection between control statements and program verification is intimate § Verification

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 淡江大學資訊管理系侯永昌 65

Conclusion § Choice of control statements beyond selection and logical pretest loops is a

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 淡江大學資訊管理系侯永昌 66