Statement-Level Control Structures

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

description

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 - PowerPoint PPT Presentation

Transcript of Statement-Level Control Structures

  • Statement-Level Control StructuresRobert W. Sebesta, Chapter 8

  • Chapter 8 TopicsIntroductionSelection StatementsIterative StatementsUnconditional BranchingGuarded CommandsConclusions

  • Control statements, control structuresControl StatementsSelecting among several alternative control flow pathsCausing the repeated execution of collections of statementsControl StructureA control statement and the collection of statements whose execution it controlsCategories include:Compound statementsSelection statementsIterative statementsUnconditional branching

  • Compound statementsAllow a collection of statements to be abstracted to a single statementA block is a compound statement which includes data declarationsSome languages have specially delimited() compound statements: beginend { }Some control constructs have built-in() delimiters(): repeatuntilcompound statement

  • Selection statementsProvide a means of choosing between 2 or more execution pathsTwo general categories:Two-way selectorsN-way selectors (or Multiple-way)

  • 2-way selection statementsGeneral form: If control_expression then clause Else clauseDesign 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?

  • 2-way selection statementsFORTRAN IVs logical if has the form IF (Boolean expr) statementExample: IF (X .GT. 10) GOTO 20 SUM = SUM + X X = X + 120 CONTINUE

  • 2-way selection statementsALGOL 60 2-way selector: if (Boolean_expr) then statement else statementNested if-elseSpecial delimiters and selection closureALGOL 68, FORTRAN 77, Ada use end if

  • 2-Way Selection StatementsALGOL 60's solution - disallow direct nesting if ... then if ... then begin begin if ... if ... then ... end else ... else ... end

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

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

  • 2-Way Selection StatementsFORTRAN 90 and Ada solution closing special wordse.g. (Ada) if ... then if ... then if ... then if ... then ... ... else end if ... else end if ... end if end ifAdvantage: readability

  • Multiple selection statementsDesign issues:What is the form and type of expression that controls the selectionMay single statements, sequences of statements, or compound statements be selectedIs the entire construct encapsulated() in a syntactic structureIs execution flow through the structure restricted to include just a single selectable segmentHow should unrepresented selector expression values be handled

  • Multiple selection statementsDesign choices:Expression is any ordinal type (int, boolean, char, enum)Segments can be single or compoundOnly one segment can be executed per execution of the constructIn 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

  • Modern multiple selectorsC, C++, Java switch statementFORTRAN arithmetic IFAda case statementPascal case statement

  • Multiple selection statementsC 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

  • C, C++, Java switch statementswitch (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);}

  • Multiple selection statementsDesign Choices: (for switch)Control expression can be only an integer typeSelectable segments can be statement sequences, blocks, or compound statementsAny 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 segmentdefault clause is for unrepresented values (if there is no default, the whole statement does nothing)

  • Multiple selection statementsFORTRAN arithmetic IF: IF (arith_expr) N1, N2, N3Example: IF (expression) 10, 20, 30 10 GO TO 40 20 GO TO 40 30 40

    The arithmetic if can be entered through any of its statements from anywhere in the program.

  • Ada case statement see page 327Descendant of the multiple-selector statement that appeared in ALGOL W in 1966Ada's case is similar to Pascal's case, except:1. Constant lists can include:Subranges e.g., 10..15Boolean OR operators e.g., 1..5 | 7 | 15..202. Lists of constants must be exhaustive()Often accomplished with others clauseThis makes it more reliable

    case expression is when choice list => statement_sequence; when choice list => statement_sequence; [when others => statement_sequence;]end case;

  • Multiple SelectionUsing ifMultiple 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

  • Multiple SelectionUsing if see page 328if count < 10 then Bag1 := True;elseif count
  • Iterative statementsThe repeated execution of a statement or compound statement is accomplished either by iteration() or recursion()Design issues:How is iteration controlledWhere should the control mechanism appear in the loopCategories:Counter-controlled loopsLogically-controlled loopsUser-located loop control mechanismsData structure based-iteration

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

  • Do Statement of Fortran 95FORTRAN 95see Page 331~332Syntax: DO label variable = initial, terminal [, stepsize]Stepsize can be any value but zeroParameters can be expressionsDesign choices:Loop variable must be INTEGERLoop variable always has its last valueThe loop variable cannot be changed in the loop, but the parameters can; because they are evaluated only once, it does not affect loop controlLoop parameters are evaluated only once

  • FORTRAN 95s Other DOSyntax: [name:] DO variable = initial, terminal [, stepsize] END DO [name]End Do instead of a labeled statementLoop variable must be an INTEGERDo Statement of Fortran 95

  • The Ada for StatementAdaSyntax:for var in [reverse] discrete_range loop ...end loop;

    Count : Float := 1.35;for Count in 1 .. 10 loopsum := sum + Count;end loop;

  • The Ada for StatementAda 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 loopThe loop variable cannot be changed in the loop, but the discrete range can; it does not affect loop controlThe discrete range is evaluated just once

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

  • For Statement of C-Based Lang.C Design Choices:1. There is no explicit() loop variable2. Irrelevant()3. Everything can be changed in the loop4. The first expression is evaluated once, but the other two are evaluated with each iterationThis loop statement is the most flexible

  • For Statement of C-Based Lang.for (count1=0,count2=1.0; count1100.0 goto outcount1 = count1 +1sum = count1+count2count2 = count2 * 2.5goto loopout:

  • For Statement of C-Based Lang.C++Differs from C in two ways:The control expression can also be BooleanThe initial expression can include variable definitions (scope is from the definition to the end of the loop body)for (int count=0;count
  • Logically-controlled loopsDesign issues:Is control pretest or posttestShould this be a special case of the counting loop statement (or a separate statement)?Exampleswhile statement (see page 335)do while (see page 335)repeat until

  • 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 gotoLogically-controlled loops

  • Language Examples (continued):4. Ada has a pretest version, but no posttest5. FORTRAN 77 and 90 have neither6. Perl has two pretest logical loops, while and until, but no posttest logical loopLogically-controlled loops

  • User-located loop controlDesign issues:Is conditional mechanism an integral part of exitShould only one loop body be exited, or can enclosing loops also be exitedExamples:Ada loop exit [loop_label] [when condition]C loops break and continue

  • 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;User-located loop control

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

  • FORTRAN 90 - EXITUnconditional; for any loop, any number of levelsFORTRAN 90 also has CYCLE, which has the same semantics as C's continueUser-located loop control

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

  • Iterative StatementsPerl has a built-in iterator for arrays and hashese.g., foreach $name (@names) { print $name }

  • Unconditional Branching - gotoProblem: readabilitySome languages do not have them: e.g., JavaLoop exit statements are restricted and somewhat camouflaged() gotos

  • Unconditional BranchingLabel forms: Unsigned int constants: Pascal (with colon) FORTRAN (no colon)Identifiers with colons: ALGOL 60, CIdentifiers in >: AdaVariables as labels: PL/I Can be assigned values and passed as parametersHighly flexible, but make programs impossible to read and difficult to implement

  • Guarded CommandsDijkstra, 1975Purpose: to support a new programming methodology (verification during program development)

  • Guarded Commands Selection: if -> [] -> ... [] -> fiSemantics: when this construct is reached, Evaluate all boolean expressionsIf more than one are true, choose one nondeterministically()If none are true, it is a runtime error

  • Guarded CommandsIdea: if the order of evaluation is not important, the program should not specify one

  • Guarded Commands2. Loops do -> [] -> ... [] -> od

  • Guarded CommandsSemantics: For each iteration:Evaluate all boolean expressionsIf more than one are true, choose one nondeterministically; then start loop againIf none are true, exit loop

  • Guarded CommandsConnection between control statements and program verification is intimateVerification is impossible with gotosVerification is possible with only selection and logical pretest loopsVerification is relatively simple with only guarded commands

  • ConclusionChoice of control statements beyond selection and logical pretest loops is a trade-off between language size and writability