1 / 21

COEN 171 - Control Structures

COEN 171 - Control Structures. Control structure general issues Compound statements Selectors (conditional structures) single two-way multiway Iteration counter controlled logical intest user-defined Guarded commands. Control Structure General Issues.

herman
Download Presentation

COEN 171 - Control Structures

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. COEN 171 - Control Structures • Control structure general issues • Compound statements • Selectors (conditional structures) • single • two-way • multiway • Iteration • counter controlled • logical • intest • user-defined • Guarded commands

  2. Control Structure General Issues • Can consider control flow at several levels • within expressions • associativity, operator precedence, order of evaluation • between program units • procedures, coroutines, concurrency • between statements • normal control flow is sequential • A control structure is a control statement and the statements whose execution it controls • To solve any programming problem, at minimum need (Bohm and Jacopini, 1966) • sequence • means of choosing between alternatives • means of repeating execution of statements

  3. Control Structure General Issues (cont.) • Much activity into control structure design in 1965 - 1975 • single entry - exit for all structures preferable • unrestricted GOTOs are problematical • Overall design question • what control statements should a language have, beyond selection and pretest logical loops? • Control structure design trades off • expressiveness (many control structures) • readability (few control structures)

  4. Compound Statements • Many (older) languages specify only single statements as targets of many actions • Compound statement is way to group many statements together so they are treated as one • begin end in most languages • Algol 60 was first to use • { } in C, C++, Java • If the compound statement can also scope variables it’s referred to as a block • Most modern languages • Modern languages use syntax to avoid compound stmts • if <condition> Algol 68 • then <statements> • else <statements> • fi

  5. Selector Statements • Allow execution of alternative statement sequences based on a test • Design issues • what is the form and type of the control expression? • what is the selectable segment form (single statement, statement sequence, compound statement)? • how is the meaning of selectors nested in then clauses of other selectors specified? • Single selector (simple conditional) • some languages (FORTRAN, BASIC) provide explicitly • IF ( <Boolean expression> ) <statement> • bad because requires GOTOs to make a 2-way selector • for that reason most make this a special case of

  6. Two-Way Selector • Also called 2-alternative conditional • if <condition> then <statement> else <statement> • “Dangling else” problem • solve with semantics (Pascal) • forbid nesting unless embedded in compound statement (ALGOL 60) • solve with reserved words to mark the end of each if statement (Algol 68, Ada) • provides both flexibility and reliability • Modula-2 follows last approach with same word used to end all statements • flexibility but reduced reliability

  7. Multiple Selector • Also called multi-alternative conditional • choose among 3 or more alternatives • Design issues • what is the form and type of the control expression? • what segments are selectable (single, compound, sequential)? • is the construct encapsulated? • is execution flow through the structure restricted to include just a single selectable segment? • what is done about unrepresented expression values? • Examples • FORTRAN arithmetic if • IF ( <integer expression> ) labelneg, label0, labelpos • not encapsulated - needs GOTOs

  8. Multiple Selector (continued) • Examples (continued) • C switch • switch (index) { • case 1: • case 3: odd += 1; • sumodd += index; • case 2: • case 4: even += 1; • sumeven += index; • default: printf (“error in switch”); } • select statement based on value in index • integer only • straight line control flow after that • default always executes • unless break executed to transfer to statement after switch

  9. Multiple Selector (continued) • Examples (continued) • case statements (implicit break in alternatives) • case index is • when 1 | 3 => odd := odd + 1; • sumodd := sumodd + 1; • when 2 | 4 => even := even + 1; • sumeven := sumeven + 1; • when others => put (“error in case”); • end case; • selector type is any ordinal • Ada requires others clause • original Pascal left undefined what happens if no case for index value • ISO Pascal says run-time error

  10. Multiple Selector (continued) • Examples (continued) • elsif (allows multiple tests like nested if, but easier to read) • if COUNT < 10 • then BAG1 := TRUE; • elsif COUNT < 100 • then BAG2 := TRUE; • elsif COUNT < 1000 • then BAG3 := TRUE; • else BAG4 := FALSE; • end if; • how is this different than case/switch or nested If-Then-Else? • syntactically? • logically? • with respect to implementation?

  11. Iteration (loops) • Categorize by • how iteration is controlled • logical loop • counter-controlled loop • where control mechanism appears in loop • pretest • before loop body • intest • in middle of loop body • posttest • after loop body • logical direction of test • termination test ( repeat - until) • stop if test true • continuation test (while - do) • loop if test true

  12. Counter-controlled loops • for I := 1 to 207 step N do • I is iteration control variable (ICV) or loop variable • 1, 207, N are loop parameters • all pretest loops except FORTRANs before 77 • ICV design issues • legal types for ICV • typically discrete • FORTRAN IV integer only • FORTRAN 77, 90 also allow real and double • can ICV be modified inside the loop • usually no • scope (Ada scopes ICV to just the loop) • value at termination • undefined (Pascal, FORTRAN IV) • last value assigned (most) • unbound (Ada)

  13. Counter-controlled loops (continued) • Effect of loop parameter changes • none (most languages) • calculate trip count from parameter values before loop execution • affect loop (Algol 60, PL/I, COBOL) • Pascal Algol 60 • for I := 1 to N do for I := 1 step 1 until N do • N := N + 1; N := N + 1; • { doubles N} { infinite loop if N >1 at start}

  14. General Loops • Combine counting and other forms of loop control • great flexibility • can be confusing • Algol 60 • for var := <list_of_stuff> do statement where <list_of_stuff> is • list of expressions • expression step expression until expression • 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, 80, 81, 82, ..., 100)

  15. General Loops (continued) • Algol 60 (continued) • ICV can’t be changed inside loop • paramters can and affect loop behavior • evaluated each time through • C • 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 • if the second expression is absent, it is an infinite loop • for (sum = 0.0, count = 0; count <= 10 && sum < 1000.0; sum = sum + count++) • everything can be changed inside the loop • and affects loop behavior • most flexible loop statement

  16. Intest Loops • Provide controlled goto mechanism with destination limited to statement following loop • C break, Modula-2 exit • FORTRAN 90 exit [ < loopname > ] • exit multiple levels of loop • Ada exit [ < loopname > ] [ when < condition > ] • Also have statements that transfer to the control mechanism at the end of the loop • C continue • FORTRAN 90 cycle [ < loopname > ] • Usually used for dealing with exceptional conditions in loop (exit if encounter something which will cause errors in rest of loop)

  17. User-Defined Iteration Control • Use order and number of elements of some data structure to control iteration • also called iterator • control mechanism is a call to a user-defined function that returns the next element in some chosen order, if there is one; else exit loop • Examples • COMMON LISP (DOLIST L) function • executes body once for each top level element in the list • C's for can be used to build a user-defined iterator • assume p is a pointer to a linked list • for (p=hdr; p; p=next(p)) { ... }

  18. Unconditional Branching • Problem is readability • so some languages don’t allow them • Modula-2, CLU, Euclid • Label forms • unsigned int constants • Pascal (with colon) • FORTRAN (no colon) • identifiers with colons • ALGOL 60, C, PL/I • identifiers in << ... >> • Ada • variables as labels • PL/I • can be assigned values and passed as parameters • highly flexible, but make program impossible to read and difficult to implement

  19. Guarded Commands • All of the previous control structures can be implemented with if-then-elses and gotos • Dijkstra proposed two non-deterministic control structures in 1975 that can’t be implemented that way • selector • if < Boolean expr > <statement sequence> • [] < Boolean expr > < statement sequence > • fi • semantics: • evaluate all guards; true guards are open • non-deterministically select one open guard and execute stmts • if no guards true, run time error guard if x >= y max := x [] y >= x max := y fi

  20. Guarded Commands (continued) • Iteration • do < Boolean expr > < statement sequence > • [] < Boolean expr > < statement sequence > • od • semantics: • evaluate guards • execute statements for one open guard • repeat until no guards are open do q1 > q2 swap (q1, q2) [] q2 > q3 swap (q2, q3) [] q3 > q4 swap (q3, q4) od

  21. Guarded Commands (continued) • Good models for concurrency • 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 • Never implemented in a real language, but similar syntax in ADA concurrency statements

More Related