Chapter 8 StatementLevel Control Structures ISBN 0 321
Chapter 8 Statement-Level Control Structures ISBN 0 -321 -49362 -1
Chapter 8 Topics • • • Introduction Selection Statements Iterative Statements Unconditional Branching Guarded Commands Conclusions Copyright © 2007 Addison-Wesley. All rights reserved. 2
Levels of Control Flow – Within expressions – Among program units – Among program statements Copyright © 2007 Addison-Wesley. All rights reserved. 3
Control Statements: Evolution • FORTRAN I control statements were based directly on IBM 704 hardware. – At the time, little was known about the inherent difficulties of programming so these were considered to be completely adequate. – By today’s standards, they would be considered to be wholly inadequate. • There was much research and many arguments in the late 1960 s and early 1970 s about this issue. – One important result: – It was proven that all algorithms represented by flowcharts can be coded with only two-way selection and pretest logical loops. – So the unconditional branch statement and its inherent problems was superfluous. – Other constructs have been added for readability/writability. • For statement; post test loop… • Need to balance… – Increase in writability vs. decrease simplicity, size and readability. Copyright © 2007 Addison-Wesley. All rights reserved. 4
Control Structure • A control structure is a control statement and the statements whose execution it controls. – Sequential – Selection – Repetition • Design question – Should a control structure have multiple entries and/ or multiple exits? Copyright © 2007 Addison-Wesley. All rights reserved. 5
Selection Statements • A selection statement provides the means of choosing between two or more paths of execution • Two general categories: – Two-way selectors – Multiple-way selectors Copyright © 2007 Addison-Wesley. All rights reserved. 6
Two-Way Selection Statements • General form: if control_expression then clause else clause • Design Issues: – What is the form and type of the control expression? – How are then and else clauses specified? – How should the meaning of nested selectors be specified? Copyright © 2007 Addison-Wesley. All rights reserved. 7
Two-Way Selection Statements • Form and type of the control expression – Must have some type of ‘syntactic marker’ to signal the beginning of the ‘then clause’. • Many languages use parentheses around the control expression. • Some use the keyword then after the control expression, in which case, the parentheses may be omitted. – The type of the control expression may be • arithmetic and/or boolean, or restricted to boolean – C 89 only supports arithmetic expressions. – C 99, C++ and Python allow arithmetic or boolean expressions. – Ada, Java, Ruby and C# restrict the type to boolean. Copyright © 2007 Addison-Wesley. All rights reserved. 8
Two-Way Selection Statements • Form of then and else clauses – – – In most languages, these clauses can appear as either a single statement or a compound statement (i. e. one or more statements “blocked” together) • Examples: C based langauges, Java. Script, and PHP. In Perl, all clauses must be compound statements. In Fortran 95, Ada, Ruby, and Python, the clauses are statement sequences. • Interesting Example in Python, where indention is used to specify compound statements. If x > y : x = y; print “case 1” • • • Historical note on early FORTRAN syntax: IF (boolean_expr) statement, where statement can be 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 This problem was solved in FORTRAN 77 Copyright © 2007 Addison-Wesley. All rights reserved. 9
Two-Way Selection Statements • Specification of the meaning of nested selectors. – Recall the grammar for an if statement from Chapter 3 <if_stmt> if <logic_expr> then <stmt> | if <logic_expr> then <stmt> else <stmt> – The problem is how to specify the syntax of the if statement so that in the case of nested if statements the meaning is clear as to which if to associate the else clause. Copyright © 2007 Addison-Wesley. All rights reserved. 10
Nesting Selectors • Java example if (sum == 0) if (count == 0) result = 0; else result = 1; • Which if gets the else? • Java's static semantics rule: else matches with the nearest if Copyright © 2007 Addison-Wesley. All rights reserved. 11
Nesting Selectors (continued) • To force an alternative semantics, compound statements may be used: if (sum == 0) { if (count == 0) result = 0; } else result = 1; • Perl requires all then and else clauses to be compound, thus requiring braces. The above code would be: if (sum == 0) { if (count == 0) { result = 0; } } else { result = 1; } Copyright © 2007 Addison-Wesley. All rights reserved. 12
Nesting Selectors (continued) • Ways to form compound statements: – Braces as in Java, C, c++, C# (Note that Perl requires compound statements…) – Indentation as in Python. . • Python Example: if (sum == 0) { if (count == 0) result = 0; } else result = 1; if sum == 0 : if count == 0 : result = 0 else: result = 1 end – Use of a special word to mark then end of the selection construct, as in Fortran 95, Ada and Ruby. • Ruby Example: if sum == 0 then if count == 0 then result = 0 end else result = 1 end Copyright © 2007 Addison-Wesley. All rights reserved. 13
Multiple-Way Selection Statements • Allow the selection of one of any number of statements or statement groups • 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? Copyright © 2007 Addison-Wesley. All rights reserved. 14
Multiple-Way Selection: Examples • Early multiple selectors: – FORTRAN arithmetic IF (a three-way selector) IF (arithmetic expression) N 1, N 2, N 3 – Segments require GOTOs – Not encapsulated (selectable segments could be anywhere) • Note that neither Perl nor Python has a multiple-selection construct. Copyright © 2007 Addison-Wesley. All rights reserved. 15
Multiple-Way Selection: Examples • Design choices for C’s switch statement 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) Must use breaks if this is needed. 4. default clause is for unrepresented values (if there is no default, the whole statement does nothing) 5. Syntax: switch (control expression) { case const_expr_1: stmt_1; … case const_expr_n: stmt_n; [default: stmt_n+1] } Copyright © 2007 Addison-Wesley. All rights reserved. 16
Multiple-Way Selection: Examples • The Ada case statement case expression is when choice list => stmt_sequence; … when choice list => stmt_sequence; [when others => stmt_sequence; ] end case; • More reliable than C’s switch (once a stmt_sequence execution is completed, control is passed to the first statement after the case statement. Implicit break… Copyright © 2007 Addison-Wesley. All rights reserved. 17
Multiple-Way Selection: Examples • • Ruby has two forms of multiple-selection constructs called case expressions. Form 1 case when boolean expression then expression [else expression] end Example: case when year % 400 == 0 then true when year % 100 == 0 then false else year % 4 == 0 end • Form 2 case expression when value then statement sequence [else statement sequence] end • Algorithm for leap year: if ( (year modulo 4 is 0) and (year modulo 100 is not 0) or (year modulo 400 is 0) ) then leap else no_leap Example case year when (1700. . 1799) then “Eighteenth” when (1800. . 1899) then “Nineteenth” when (1900. . 1999) then “Twentieth” else “Other” end Copyright © 2007 Addison-Wesley. All rights reserved. 18
Multiple-Way Selection Using if • • Multiple Selectors can appear as direct extensions to two-way selectors, using else-if clauses. Ada example: • Python example: if. . . then. . . elsif. . . then. . . else. . . end if if count < 10 : bag 1 = True elif count < 100 : bag 2 = True elif count < 1000 : bag 3 = True • Ruby example: case when count < 10 then bag 1 = True when count < 100 then bag 2 = True when count < 1000 then bag 3 = True Copyright © 2007 Addison-Wesley. All rights reserved. 19
Iterative Statements • The repeated execution of a statement or compound statement is accomplished either by iteration or recursion. • General design issues for iteration control statements: 1. How is iteration controlled? 2. Where is the control mechanism in the loop? Copyright © 2007 Addison-Wesley. All rights reserved. 20
Counter-Controlled Loops • A counting iterative statement has a loop variable, and a means of specifying the initial and terminal values of the loop variable, and stepsize values. • 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? Copyright © 2007 Addison-Wesley. All rights reserved. 21
Iterative Statements: Examples • FORTRAN 90 syntax: DO label loop variable = initial, terminal [, stepsize] where, label is that of the last statement in the loop body and stepsize can be any value but zero and defaults to 1. Do 10 Index = 1, 10 … 10 Continue • FORTRAN 95 syntax • Design choices: Do Index = 1, 10 … End Do – Loop parameters can be expressions of positive or negative value. – – – Loop variable must be an INTEGER Loop variable maintains its last assigned value Loop parameters are evaluated at the beginning of the execution and the values are used to compute an interation count, an internal value • • Therefore, while the parameters can be changed it does not affect loop control. Operational semantics description on page 359 Copyright © 2007 Addison-Wesley. All rights reserved. 22
Iterative Statements • Pascal’s for statement 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 Copyright © 2007 Addison-Wesley. All rights reserved. 23
Iterative Statements: Examples • Ada for var in [reverse] discrete_range loop. . . end loop • A discrete range is a sub-range of an integer or enumeration type • Scope of the loop variable is the range of the loop • Loop variable is implicitly undeclared after loop termination Copyright © 2007 Addison-Wesley. All rights reserved. 24
Iterative Statements: Examples • C’s for statement 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 • There is no explicit loop variable • Everything can be changed in the loop • The first expression is evaluated once, but the other two are evaluated with each iteration Copyright © 2007 Addison-Wesley. All rights reserved. 25
Iterative Statements: Examples • 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) for (int i = 0; i < count; i++) … • Java and C# – Differs from C++ in that the control expression must be Boolean Copyright © 2007 Addison-Wesley. All rights reserved. 26
Iterative Statements: Examples • Python example for loop_variable in object: loop body else: else clause for count in [2, 4, 6] : print count // prints 2, 4 , 6 for count in range (5) : print count // prints 0, 1, 2, 3, 4 for count in range (2, 7) : print count // prints 2, 3, 4, 5, 6 for count in range (0, 8, 2) : print count // prints 0, 2, 4, 6 Copyright © 2007 Addison-Wesley. All rights reserved. 27
Iterative Statements: Logically-Controlled Loops • • • Repetition control is based on a Boolean Design issues: – Pre-test or post-test? – Should the logically controlled loop be a special case of the counting loop statement ? – Use an expression rather than a counter General forms: pre–test form while (ctrl_expr) loop body Copyright © 2007 Addison-Wesley. All rights reserved. post–test form do loop body while (ctrl_expr) 28
Iterative Statements: Logically. Controlled Loops: Examples • Pascal has separate pre-test and post-test logical loop statements. – • C and C++ also have both – – • while-do and repeat-until The control expression for the post-test version is treated just like in the pre-test case. • while-do and do- while It is legal to branch into both while and do loop bodies. Java is like C, except – – the control expression must be Boolean. the body can only be entered at the beginning • Java has no goto Copyright © 2007 Addison-Wesley. All rights reserved. 29
Iterative Statements: Logically. Controlled Loops: Examples • Ada has a pretest version, but no post-test • FORTRAN 77 and 90 have neither • Perl and Ruby have two pre-test logical loops, while and until – Perl has two posttest loops. Copyright © 2007 Addison-Wesley. All rights reserved. 30
Iterative Statements: User-Located Loop Control Mechanisms • Sometimes languages support statements that allow the loop control to be other than top or bottom (i. e. pre-test or posttest) • Support for such loop control can be supported with a break statement or a goto. • Design issues for nested loops 1. Should the conditional be part of the exit? 2. Should control be transferable out of more than one loop? And to where? Copyright © 2007 Addison-Wesley. All rights reserved. 31
Iterative Statements: User-Located Loop Control Mechanisms break and continue • • C, C++, Python, Ruby and C# have unconditional unlabeled exits using break. Java (break) and Perl (last) have unconditional labeled exits. – Unconditional break can be used for switch or any loop at one level only. while (sum < 1000) { getnext(value); if (value < 0) break; sum += value; } • In the labeled break of Java and C# control transfers to the label outer. Loop: for (r = 0; r < nr; r++) for (c = 0; c < nc; c++) } sum += mat[r][c] if (sum > 1000. 0) break outer. Loop; } • An alternative: continue statement; it skips the remainder of this iteration, but does not exit the loop. while (sum < 1000) { getnext(value); if (value < 0) continue; sum += value; } Copyright © 2007 Addison-Wesley. All rights reserved. 32
Iterative Statements: Iteration Based on Data Structures • Number of elements of in a data structure control loop iteration. • Control mechanism is a call to an iterator function that returns the next element in some chosen order, if there is one; else loop is terminate. • C's for can be used to build a user-defined iterator: for (p=root; p==NULL; traverse(p)){ } Copyright © 2007 Addison-Wesley. All rights reserved. 33
Iterative Statements: Iteration Based on Data Structures (continued) • C#’s foreach statement iterates on the elements of arrays and other collections: Strings[] = str. List = {“Bob”, “Carol”, “Ted”}; foreach (Strings name in str. List) Console. Write. Line (“Name: {0}”, name); • The notation {0} indicates the position in the string to be displayed Copyright © 2007 Addison-Wesley. All rights reserved. 34
Unconditional Branching • Transfers execution control to a specified place in the program • Represented one of the most heated debates in 1960’s and 1970’s • Well-known mechanism: goto statement • Major concern: Readability • Some languages do not support goto statement (e. g. , Module-2 and Java) • C# offers goto statement (can be used in switch statements) • Loop exit statements are restricted and somewhat camouflaged goto’s Copyright © 2007 Addison-Wesley. All rights reserved. 35
Guarded Commands • Suggested by Dijkstra • Purpose: to support a new programming methodology that supported verification (correctness) during development • Basis for two linguistic mechanisms for concurrent programming (in CSP and Ada) • Basic Idea: if the order of evaluation is not important, the program should not specify one Copyright © 2007 Addison-Wesley. All rights reserved. 36
Selection Guarded Command • Form if <Boolean exp> -> <statement> [] <Boolean exp> -> <statement>. . . [] <Boolean exp> -> <statement> Fi • Semantics: when 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 Copyright © 2007 Addison-Wesley. All rights reserved. 37
Copyright © 2007 Addison-Wesley. All rights reserved. 38
Selection Guarded Command: Illustrated Copyright © 2007 Addison-Wesley. All rights reserved. 39
Selection Guarded Command • Example 1 if i=0 -> sum : = sum + i [] i > j -> sum : = sum + i [] j > i -> sum : = sum + i fi Case of i = 0 and j > i, then chooses nondeterministically between sum : = sum + i and sum : = sum + i Case of i != 0 and i == j, then run-time error. • Example 2 if x > y -> max : = x [] y >= x -> max : = y fi Conventional solution complicates formal analysis: if (x >= y) max = x; else max = y; Copyright © 2007 Addison-Wesley. All rights reserved. 40
Loop Guarded Command • Form do <Boolean> -> <statement> [] <Boolean> -> <statement>. . . [] <Boolean> -> <statement> od • 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 Copyright © 2007 Addison-Wesley. All rights reserved. 41
Copyright © 2007 Addison-Wesley. All rights reserved. 42
Loop Guarded Command • Example 1 page 375 sort the values so that – q 1 < q 2 < q 3 < q 4. Do q 1 > q 2 -> temp : = q 1; q 1 : = q 2; q 2 : = temp; [] q 2 > q 3 -> temp: q 2; … [] q 3 > q 4 -> temp: = q 3; … od Copyright © 2007 Addison-Wesley. All rights reserved. 43
Guarded Commands: Rationale • Connection between control statements and program verification is intimate • Verification is impossible with goto statements • Verification is possible with only selection and logical pretest loops • Verification is relatively simple with only guarded commands Copyright © 2007 Addison-Wesley. All rights reserved. 44
Conclusion • Variety of statement-level structures • Choice of control statements beyond selection and logical pretest loops is a trade-off between language size and writability • Functional and logic programming languages are quite different control structures Copyright © 2007 Addison-Wesley. All rights reserved. 45
- Slides: 45