New version page

CU-Boulder CSCI 3155 - Control flow

This preview shows page 1-2-3-4-5-6 out of 18 pages.

View Full Document
View Full Document

End of preview. Want to read all 18 pages?

Upload your study docs or become a GradeBuddy member to access this document.

View Full Document
Unformatted text preview:

1Control flowAmer DiwanWhat is control flow• The order in which operations are executed in aprogram• e.g. in C++ like language,– a = 1;b = a + 1;– if a > 100 then b = a - 1; else b = a + 1;– a - b + c2Organization• This topic– A look at basic control-flow:• Within expressions• Between statements• Next topic (chapter 8 of text)– A closer look at procedure calls– Advanced topics: exception handling and closuresControl flow within expressions:associativity and precedence• Which operators group more tightly (and thusexecute first)• In Java all binary operators except assignments areleft associative– 3 - 3 + 5– x = y = f()(assignments evaluate to the value being assigned)3Precedence and associativity (cont.)• In C++ arithmetic operators (+, -, *, ...) havehigher precedence than relational operators (<, ...)– x + y < z + w– x + y == zWhat if a language does not specifydetailed associativity and precedence• E.g., in Smalltalk, all operators are of equalprecedence– a + b * c results in (a+b)*c– Must use parenthesis liberally!• E.g., in Ada exponentiation does not associate– 4 ** 3**2 is illegal: must write (4**3)**2 or4**(3**2)4Ordering within expressions• x = a - f() - c * d equivalent to:– t1 = a - f();t2 = c * d;x = t1 - t2; or– t2 = c * d;t1 = a - f();x - t1 - t2;• What’s the difference?Compiler optimizations also likeflexibility in reordering expressions• t = c * d;x = a - f() - c * d;• If the compiler has the freedom, it can rewrite theabove as:• t = c * d;x = a - f() - t;• Most languages allow the compiler to reorder asneeded• Java is an exception: requires left-to-rightevaluation5Control flow within expressions: shortcircuit evaluation• boolean b = very_unlikely_condition &&very_expensive_condition• boolean b = very_expensive_condition &&very_unlikely_condition• An operator is short-circuit if the remainder ofcomputation can be skipped as soon as the truthvalue is discoveredShort-circuit evaluation:not just for performance• if (p != nil && p.next.value == 10) { ...}• The compiler must respect short-circuit operations(i.e., “short-circuit” is not a performance hint!)6Side effects and control flow withinexpressions• The order of evaluation of subexpressions isparticularly important if the subexpressions haveside-effects– Modify variables– Perform I/O– Cause errors/exceptionsReferential transparency• An expression is referentially transparent if giventhe same inputs it always produces the sameoutput– 4– int f(i) { i + 1; }– int f(i) { i + j; } and j is not a constant• An RT expression can be reordered easily withoutchanging the meaning of the program7Control flow between statements:Structured versus unstructured• Unstructured: goto, jeq, ...– Generally resembles assembly instructions• Structured: if...then...else, while..., for...• Structured statements encourage top-downprogramming:– programming by successive refinementWhy structured or unstructured?• if x < y goto 10call fgoto 2010:call g20:• if x < y then call felse call gendPrograms that use structured control flow are easier to read8...but sometimes unstructuredmakes sense• while !please_break && i < 10 do while !please_break && j < 10 do if a == NIL then please_break = true endend• while i < 10 do while j < 10 do if a == NIL then goto exit; endendexit:We will now look at a selection of control constructs in modern programming languagesControl flow: Sequencing• One statement appearing after another• i = 1;j = i * 7;• Does sequencing make sense if there are no sideeffects?9Control flow: selection• Selects which statements to execute next• e.g.,– if-then-else– case/switch statement (next slide)– pattern matching (later in the term)Case/switch statements• Supports special case for cascaded if-then-else– Comparisons must compare to an ordinal constant(integer, enumeration type)– switch f() { case 1: do_something1 case 4: do_something2 case 5: do_something3 default: do_something4}10Why case/switch statements?• Compact• May be more efficient than if-then-elseswitch f() { case 1: B1 case 4: B2 case 5: B3 default: B4}goto A[f()-1]; (assuming f()returns values between 1 and 5) 12345B1B4B2B3AMore on switch statements• Efficiency is one reason why case labels need tobe ordinal constants• Another reason: simplicityswitch f() { case x: B1 case y: B2 case z: B3 default: B4}•What if both x and y match?•What if x, y, and z have side effects?11Guarded commands:a generalization of switch statements• switch f() {  x: B1  y: B2  z: B3}• Guards can be arbitrary expressions (but side-effect free)• If more than one matches, it picks one at randomControl flow: Iteration• A conditional that keeps executing as long as thecondition is true• e.g: while, for, loop, repeat-until, ...12Logically controlled loops• while, do-while, repeat-until, ...• while i < 10 do a[i] := 0 i := i + 1end• WHILE checks condition at the top. REPEAT-UNTIL checks condition at the bottomEnumeration controlled loops• FOR i = first TO last DO ...END• i is often automatically declared and often has thescope of the loop body13Access to index variable inside the loop• FOR i := A’first TO A’last DO A[i] := 0;END• FOR i = A’first TO A’last DO A[i] := 0; i := i + 1;ENDLanguages with enumeration controlled loops frequently do not allow modification to index variableFOR statement example from Modula-3• FOR id := first TO last BY step DO S END• “The identifier id denotes a readonly variablewhose scope is S and whose type is the commonbasetype of first and last”• “...the statement steps id thorough the values first,first+step, first+2*step, ..., stopping when thevalue of id passes last... If step is negative the loopiterates downwards”14Example continued• FOR i := 1 TO 10 BY 1DO A[i] := 0;END• FOR i := 10 TO 1 BY -1DO A[i] := 0;END• FOR i := 10 TO 1 BY 1DO A[i] := 0;END• FOR i := x TO y BY z DO A[i] := 0;ENDSome subtleties with FOR statements• Overflow– FOR i := 1 TO n BY 1 DO print(i)END– What if ‘n’ is max-int?• STEP sign determines whether the index variablesneeds to go above or below “upper”15Advantages and disadvantages ofenumeration controlled loops• Expressiveness– Can concisely and cleanly represent some kinds of loops• Simplicity– All loop control information is in the


View Full Document
Loading Unlocking...
Login

Join to view Control flow and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Control flow and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?