Statement Level Control Structures
Total Page:16
File Type:pdf, Size:1020Kb
Chapter 8 Topics Chapter 8 • Introduction • Selection Statements • Iterative Statements • Unconditional Branching Statement-Level • Guarded Commands Control Structures • Conclusions Levels of Control Flow Evolution of Control Statements – Within expressions • FORTRAN I control statements were based – Controlled by operator precedence and associativity directly on IBM 704 hardware – Among program units • Much research and argument in the 1960s – Function call and concurrency about the issue – Among program statements – One important result: It was proven that all algorithms represented by flowcharts can be coded – Control statements and control structures with only two-way selection and pretest logical loops (Bohm and Jacopini, Structured Programming Theorem, 1966) – Any language with these features is “Turing- complete” – can compute anything that is computable Goto Statement Control Structures • At the machine level we really have only • A control structure is a control statement and conditional and unconditional branches (or the statements whose execution it controls gotos) • Programmers care more about readability and • Using conditional gotos we can create any kind writ ability than theoretical results of selection or iteration structure – While we can build very small languages and/or use • But undisciplined use of gotos can create very simple control structures, we would like to an spaghetti code expressive language with readable code – Languages often provide multiple control structure for iteration and selection to aid readability and writability 1 Design Issues Selection Statements • Multiple Exits • A selection statement provides the means of – Not really a design issue at all. choosing between two or more paths of – All languages allow for multiple exits execution • If the target is always the first statement after the end • Two general categories: of the structure, not an issue – Two-way selectors • If the target is unrestricted then the question reduces to whether or not we allow GOTO statements – Multiple-way selectors • Multiple Entry Points – Only possible if language already includes goto statements and labels (names for statements and thus possible targets) Selection Statement Design Issues • IfStatement if ( Expression ) Statement • What is the form and type of the control [ else Statement ] expression? • Example: if (a > b) • How are the then and else clauses z = a; specified? else z = b; • How should the meaning of nested selectors • If the test expression is true, then the output be specified? state of the conditional is the output state of the then branch, • else the output state of the conditional is the output state of the else branch. Control Expression Clause Form • If the then reserved word or some other syntactic • In many contemporary languages, the then and else marker is not used to introduce the then clause, the clauses can be single statements or compound control expression is placed in parentheses (typical of statements C-like languages) • In Perl, all clauses must be delimited by braces (they • Early C did not have a Boolean must be compound) – Selection clauses were integer or arithmetic expressions • In Fortran 95, Ada, and Ruby, clauses are statement – Many languages transparently coerce the result of a control sequences expression to Boolean • Python uses indentation to define clauses • 0 = false, non-zero = true • Empty string = false, non-empty string = true if x > y : • But watch out: some languages coerce the string to an integer x = y first, then test for 0 print "case 1“ • In languages such as Ada, Java, Ruby, and C#, the • In Python : or then can be used control expression must be explicitly Boolean 2 Nesting Selectors Nesting Selectors (continued) • Java example • To force an alternative semantics, compound if (sum == 0) statements may be used: if (count == 0) if (sum == 0) { result = 0; if (count == 0) else result = 1; result = 0; • Which if gets the else? } • Java's static semantics rule: else matches else result = 1; with the nearest if • The above solution is used in C, C++, and C# • Perl requires that all then and else clauses to be compound Ending with Reserved Words Nesting Selectors (continued) • Can avoid the issue of nested selection • Python statements using a reserved word to end if sum == 0 : clauses if count == 0 : • Ex: Ruby result = 0 if sum == 0 then else : if count == 0 then result = 1 result = 0 else result = 1 end end Multiple-Way Selection Statements Two types of multiway selection • Select among any number of control paths • Multiway selection is used for two different, • We really only need one way to express selection but similar purposes: semantics 1. Providing multiple control paths based on the – We can use a multi-way selector to express 2-way selection value of a single scalar with a relative small range semantics of possible ordinal values – We can use a 2-way selector to express multi-way selection semantics 2. Flattening deeply nested if statements consisting • Either alternative is syntactically clumsy and makes of mutually-exclusive cases programs harder to read and write. • Case or Switch statements are usually used for the first purpose and else-if statements for the latter – Some languages combine both purposes into a single flexible case statement 3 Case/Switch Design Issues Switch or Case statement 1. What is the form and type of the control • Selection of a small set of ordinal values expression? – Started with Fortran computed GOTO GO TO (100, 87, 345, 190, 52) COUNT 2. How are the selectable segments specified? – Semantics: if count = 1 goto 100, if count = 2 goto 87 etc. 3. Is execution flow through the structure – Can be implemented as a jump table restricted to include just a single selectable • Switch or Case entry statement contains a control segment? expression • Body of statement contains multiple tests for values of 4. How are case values specified? control expression with associated block of code 5. What is done about unrepresented control • For efficient implementation (jump table) control expression values? expression should resolve to relatively small number of discrete values Switch in C-Like Languages C Switch switch(n) { case 0: • Design choices for C’s switch statement printf("You typed zero.\n"); break; 1. Control expression can be only an integer type case 1: 2. Selectable segments can be statement sequences, blocks, or case 9: compound statements printf("n is a perfect square\n"); break; 3. Any number of segments can be executed in one execution of case 2: the construct (there is no implicit branch at the end of printf("n is an even number\n"); selectable segments) case 3: 4. default clause is for unrepresented values (if there is no case 5: case 7: default, the whole statement does nothing) printf("n is a prime number\n"); break; • The C switch statement was designed to be as case 4: flexible as possible printf("n is a perfect square\n"); case 6: • For nearly all normal usage the flexibility is case 8: printf("n is an even number\n"); much greater than needed and the requirement break; for an explicit break to terminate execution default: printf("Only single-digit numbers are allowed\n"); seems like a design error break; } C# Changes C# • C# has a static semantics rule that disallows switch (expression) the implicit execution of more than one { segment case constant-expression: – Each selectable segment must end with an statement unconditional branch (goto, return, continue or break) jump-statement • Control expression and the case constants can [default: be strings statement jump-statement] } 4 C# An interesting (ab)use of switch in PHP switch (value){ function flavor($type = null) { switch ($type) { case -1: default: $type = null; minusone++; case $array[] = "chocolate": if ($type != null) { break; $array = array($type); break; } case 0: case $array[] = "strawberry": if ($type != null) { zeros++; $array = array($type); break; goto case 1; } case $array[] = "vanilla": case 1: if ($type != null) { $array = array($type); nonnegs++; break; break; } } default: if ( (count($array) != 1) ) { return "Flavors available: " . implode(", ", $array); return; } else { return "Flavor selected: " . implode(", ", $array); } } } An interesting (ab)use of switch in PHP Ada • Functionality is attributable to semantics of • Ada assignment expressions case expression is when choice list => stmt_sequence; echo flavor() . "<br>"; … /* Flavors available: chocolate, when choice list => stmt_sequence; strawberry, vanilla */ when others => stmt_sequence;] echo flavor("banana") . "<br>"; end case; /* Flavors available: chocolate, strawberry, vanilla */ • More reliable than C’s switch (once a stmt_sequence echo flavor("chocolate") . "<br>"; execution is completed, control is passed to the first /* Flavor selected: chocolate */ statement after the case statement 1-28 Case in Ada Ada Design Choices type Directions is (North, South, East, West); Heading : Directions; • Ada design choices: case Heading is 1. Expression can be any ordinal type when North => 2. Segments can be single or compound Y := Y + 1; when South => 3. Only one segment can be executed per execution of Y := Y - 1; the construct when East => 4. Unrepresented values are not allowed X := X + 1; • Constant List Forms: when West => X := X - 1; 1. A list of constants end case; 2. Can include: Ada also supports choice lists: - Subranges - Boolean OR operators (|) case ch is when ‘A’..’Z’|’a’..’z’ => 5 Switch in Ruby Perl, Python, Lua case n when 0 then puts 'You typed zero' • Perl, Python and Lua do not have when 1, 9 then puts 'n is a perfect square' when 2 then multiple-selection constructs but the puts 'n is a prime number' puts 'n is an even number' same effect can be obtained using when 3, 5, 7 then puts 'n is a prime number' when 4, 6, 8 then puts 'n is an even number' else-if structures else puts 'Only single-digit numbers are allowed‘ end • Switch can also return a value in Ruby catfood = case when cat.age <= 1: junior when cat.age > 10: senior else normal end Implementing Multiple Selection A Deeply Nested If if (grade > 89) { • Four main techniques ltr = 'A'; 1.