• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
8 statement-level control structure
 

8 statement-level control structure

on

  • 542 views

 

Statistics

Views

Total Views
542
Views on SlideShare
542
Embed Views
0

Actions

Likes
0
Downloads
0
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    8 statement-level control structure 8 statement-level control structure Document Transcript

    • ICS 313 - Fundamentals of Programming Languages 18. Statement-Level Control Structure8.1 IntroductionLevels of Control FlowWithin expressionsAmong program unitsAmong program statementsEvolutionFORTRAN I control statements were based directly on IBM 704 hardwareMuch research and argument in the1960s about the issueOne important result: It was proven that all flowcharts can be coded withonly two-way selection and pretest logical loopsA control structure is a control statement and the statements whoseexecution it controlsOverall Design QuestionWhat control statements should a language have, beyond selection andpretest logical loops?
    • ICS 313 - Fundamentals of Programming Languages 28.2 Compound statementsIntroduced by ALGOL 60A block is a compound statement that can define anew scope (with local variables)8.3 Selection StatementsDesign IssuesWhat is the form and type of the control expression?What is the selectable segment form (single statement, statementsequence, compound statement)?How should the meaning of nested selectors be specified?Single-Way ExamplesFORTRAN IF: IF (boolean_expr) statementProblem: can select only a single statement; to select more, a GOTO mustbe used, as in the following exampleIF (.NOT. condition) GOTO 20......20 CONTINUENegative logic is bad for readabilityThis problem was solved in FORTRAN 77Most later languages allow compounds for the selectable segment of theirsingle-way selectors
    • ICS 313 - Fundamentals of Programming Languages 38.3 Selection Statements (continued)Two-way Selector ExamplesALGOL 60 if:if (boolean_expr)then statement (the then clause)else statement (the else clause)The statements could be single or compoundNested Selectorse.g. (Java)if ...if ......else ...Which if gets the else?Javas static semantics rule: else goes with the nearest if8.3 Selection Statements (continued)ALGOL 60s solution - disallow direct nestingif ... then if ... thenbegin beginif ... if ... then ...then ... endelse ... else ...endFORTRAN 90 and Ada solution - closing special wordse.g. (Ada)if ... then if ... thenif ... then if ... then... ...else end if... elseend if ...end if end ifAdvantage: flexibility and readability
    • ICS 313 - Fundamentals of Programming Languages 48.3 Selection Statements (continued)Multiple Selection ConstructsDesign IssuesWhat is the form and type of the control expression?What segments are selectable (single, compound, sequences)?Is the entire construct encapsulated?Is execution flow through the structure restricted to include just asingle selectable segment?What is done about unrepresented expression values?Early Multiple SelectorsFORTRAN arithmetic IF (a three-way selector) IF (arithmeticexpression) N1, N2, N3Bad aspectsNot encapsulated (selectable segments could be anywhere)Segments require GOTOsFORTRAN computed GOTO and assigned GOTO8.3 Selection Statements (continued)Modern Multiple SelectorsPascal case (from Hoares contribution to ALGOL W)case expression ofconstant_list_1 : statement_1;...constant_list_n : statement_nendDesign choicesExpression is any ordinal type (int, boolean, char, enum)Segments can be single or compoundConstruct is encapsulatedOnly one segment can be executed per execution of the constructIn Wirths 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
    • ICS 313 - Fundamentals of Programming Languages 58.3 Selection Statements (continued)The C, C++, and Java switchswitch (expression) {constant_expression_1 : statement_1;...constant_expression_n : statement_n;[default: statement_n+1]}Design Choices: (for switch)Control expression can be only an integer typeSelectable segments can be statement sequences, blocks, or compoundstatementsConstruct is encapsulatedAny number of segments can be executed in one execution of the construct (there isno implicit branch at the end of selectable segments) (a trade-off between reliabilityand 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 wholestatement does nothing)8.3 Selection Statements (continued)Adas case is similar to Pascals case, except:Constant lists can include:Subranges e.g., 10..15Boolean OR operatorse.g., 1..5 | 7 | 15..20Lists of constants must be exhaustiveOften accomplished with others clauseThis makes it more reliableMultiple Selectors can appear as direct extensions to two-way selectors, usingelse-if clauses (ALGOL 68, FORTRAN 90, Ada)Ada:if ...then ...elsif ...then ...elsif ...then ...else ...end ifFar more readable than deeply nested ifsAllows a Boolean gate on every selectable group
    • ICS 313 - Fundamentals of Programming Languages 68.4 Iterative StatementsThe repeated execution of a statement or compound statement isaccomplished either by iteration or recursion; here we look atiteration, because recursion is unit-level controlGeneral design Issues for iteration control statementsHow is iteration controlled?Where is the control mechanism in the loop?Counter-Controlled LoopsDesign IssuesWhat are the type and scope of the loop var?What is the value of the loop var at loop termination?Should it be legal for the loop var or loop parameters to be changed inthe loop body, and if so, does the change affect loop control?Should the loop parameters be evaluated only once, or once for everyiteration?8.4 Iterative Statements (continued)FORTRAN 90Syntax: DO label var = start, finish [, stepsize]Stepsize can be any value but zeroParameters can be expressionsDesign choices:Loop var must be INTEGERLoop var always has its last valueThe loop var 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 onceFORTRAN 90’s Other DOSyntax[name:] DO variable = initial, terminal [, stepsize]…END DO [name]Loop var must be an INTEGER
    • ICS 313 - Fundamentals of Programming Languages 78.4 Iterative Statements (continued)ALGOL 60Syntax: for var := <list_of_stuff> do statement,where <list_of_stuff> can havelist of expressionsexpression step expression until expressionexpression while boolean_expressionfor 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)ALGOL 60 Design choicesControl expression can be int or real; its scope is whatever it isdeclared to beControl var has its last assigned value after loop terminationThe loop var cannot be changed in the loop, but the parameters can,and when they are, it affects loop controlParameters are evaluated with every iteration, making it very complexand difficult to read8.4 Iterative Statements (continued)PascalSyntax:for variable := initial (to | downto) final do statementDesign ChoicesLoop var must be an ordinal type of usual scopeAfter normal termination, loop var is undefinedThe loop var cannot be changed in the loop; the loop parameters can be changed, but they areevaluated just once, so it does not affect loop controlAdaSyntax:for var in [reverse] discrete_range loop...end loopDesign choicesType of the loop var is that of the discrete range; its scope is the loop body (it is implicitlydeclared)The loop var does not exist outside the loopThe loop var cannot be changed in the loop, but the discrete range can; it does not affectloop controlThe discrete range is evaluated just once
    • ICS 313 - Fundamentals of Programming Languages 88.4 Iterative Statements (continued)CSyntaxfor ([expr_1] ; [expr_2] ; [expr_3]) statementThe expressions can be whole statements, or even statementsequences, with the statements separated by commasThe value of a multiple-statement expression is the value of the laststatement in the expression e.g.,for (i = 0, j = 10; j == i; i++) …If the second expression is absent, it is an infinite loopDesign Choices:There is no explicit loop varIrrelevantEverything can be changed in the loopThe first expression is evaluated once, but the other two are evaluated with each iterationThis loop statement is the most flexible8.4 Iterative Statements (continued)C++Differs from C in two ways:The control expression can also be BooleanThe initial expression can include variable definitions (scope is from thedefinition to the end of the loop body)JavaDiffers from C++ in that the control expression must beBoolean
    • ICS 313 - Fundamentals of Programming Languages 98.4 Iterative Statements (continued)Logically-Controlled LoopsDesign IssuesPretest or postest?Should this be a special case of the counting loop statement (or a separatestatement)?Language ExamplesPascal has separate pretest and posttest logical loop statements (while-do andrepeat-until)C and C++ also have both, but the control expression for the posttest version istreated just like in the pretest case (while - do and do - while)Java is like C, except the control expression must be Boolean (and the body canonly be entered at the beginning -- Java has no goto)Ada has a pretest version, but no posttestFORTRAN 77 and 90 have neitherPerl has two pretest logical loops, while and until, but no posttest logical loop8.4 Iterative Statements (continued)User-Located Loop Control MechanismsDesign issues:Should the conditional be part of the exit?Should the mechanism be allowed in an already controlled loop?Should control be transferable out of more than one loop?ExamplesAda - conditional or unconditional; for any loop; any number of levelsfor ... loop LOOP1:... while ... loopexit when ... ...... LOOP2:end loop for ... loop...exit LOOP1 when .....end loop LOOP2;...end loop LOOP1;
    • ICS 313 - Fundamentals of Programming Languages 108.4 Iterative Statements (continued)C , C++, and Java - breakUnconditional; for any loop or switch; one level only (except Java’s can have alabel)There is also has a continue statement for loops; it skips the remainder of thisiteration, but does not exit the loopFORTRAN 90 - EXITUnconditional; for any loop, any number of levelsFORTRAN 90 also has CYCLE, which has the same semantics as Cs continueIteration Based on Data StructuresConcept: use order and number of elements of some datastructure to control iterationControl mechanism is a call to a function that returns the nextelement in some chosen order, if there is one; else exit loopCs for can be used to build a user-defined iteratore.g. for (p=hdr; p; p=next(p)) { ... }Perl has a built-in iterator for arrays and hashese.g., foreach $name (@names) { print $name }8.5 Unconditional BranchingProblem: readabilitySome languages do not have them: e.g., JavaLoop exit statements are restricted and somewhatcamouflaged goto’sLabel formsUnsigned int constants: Pascal (with colon)FORTRAN (no colon)Identifiers with colons: ALGOL 60, CIdentifiers in << ... >>: AdaVariables as labels: PL/ICan be assigned values and passed as parametersHighly flexible, but make programs impossible to read and difficult to implement
    • ICS 313 - Fundamentals of Programming Languages 118.6 Guarded CommandsDijkstra, 1975Purpose: to support a new programming methodology (verificationduring program development)Selection: if <boolean> -> <statement>[] <boolean> -> <statement>...[] <boolean> -> <statement>fiSemantics: when this construct is reached,Evaluate all boolean expressionsIf more than one are true, choose one nondeterministicallyIf none are true, it is a runtime errorIdea: if the order of evaluation is not important, the program should notspecify oneSee book examples (pp. 339, 340)8.6 Guarded Commands (continued)Loops do <boolean> -> <statement>[] <boolean> -> <statement>...[] <boolean> -> <statement>odSemantics: For each iterationEvaluate all boolean expressionsIf more than one are true, choose one nondeterministically; then start loop againIf none are true, exit loop--> See book example (p. 340)Connection 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 commandsChapter Conclusion: Choice of control statements beyond selection and logicalpretest loops is a trade-off between language size and writability