Chapter 7 Control I Expressions and Statements Expressions Conditional Statements and Guards Loops and Variation on WHILE The GOTO Controversy Exception Handling
Values and Effects Important Concepts in Programming Languages Values Effects Expressions Statements Functions Complicating Factors expressions with side effects functions with side effects Procedures subprograms Programming Languages 2
Control Structures Implicit Control Flow the evaluation order of operands in an expression the execution in sequence of statements Explicit Control Flow structured control statements single-entry, single-exit in principle Preemptive Control Mechanism exception handling Programming Languages 3
Expressions Expressions are composed of operators and operands functions and arguments Classifying Operands According to the number of operands required unary - x binary x + y ternary x? y : z According to the positions of the operators infix x + y most languages prefix + x y LISP postfix x y + Postscript, FORTH Programming Languages 4
Evaluation Order of Expressions Applicative Order Evaluation operands are evaluated first and then, the operators are applied to the operands Normal Order Evaluation operators are evaluated before the operands What does it mean to evaluate operators? explained later Programming Languages 5
Applicative Order Example (3+4)*(5-6) 7*(5-6) (3+4)*-1 7*-1-7 In most languages, the evaluation order of operands (or the arguments) is not specified. Programming Languages 6
Evaluation Order and Side-Effects When the expressions may have side-effects, programs may be incorrect due to this fact. Example In the right C program, the function f has a side-effect. Guess the output! Some operators may have side effects Assignment operators in C #include <stdio.h> int x = 1; int f(void) { x += 1; return x; } int p( int a, int b) { return a + b; } main() { printf("%d\n",p(x,f())); return 0; } Programming Languages 7
Evaluation Order Specified Operators Sequence Operators x = (y+1,x+y,x+1) Logical And and Logical Or logical binary operators may be short-circuited If Expressions c? e1 : e2 Case Expressions case e0 of a => e1 b => e2 c => e3 ; Programming Languages 8
Short-Circuit Evaluation The short-circuit evaluation enables compact notations with the short-circuit evaluation if (x!= 0 && y%x == 1)... without the short-circuit evaluation if (x!= 0) if (y%x == 1)... Some languages support the both kinds of Boolean operators In Ada, and, or and then, or else not short-circuited short-circuited Programming Languages 9
Normal Order Evaluation The evaluation of operators? Think of user defined functions. int double(int x){ return x+x; } int square(int x){ return x*x; } square(double(2)) double(2)*double(2) (2+2)*double(2) double(2)*(2+2) 4*double(2) double(2)*4 4*(2+2) (2+2)*4 4*4 16 Programming Languages 10
Conditional Statements In a Conditional Statement, a group of statements is executed only under certain conditions. Kinds of Conditional Statements Single or Binary Selection: if and if-else statement Multiple Selection: case- and switch-statement Programming Languages 11
Guarded If Due to E. W. Dijkstra Nondeterministic selection of statements if B 1 -> S 1 B 2 -> S 2... When one of B i, say B k, is true, then the S k is executed. B n -> S n fi Programming Languages 12
Dangling-Else Problem Which if is the following else matched? if (e1) if (e2) s1 else s2 Solutions of Dangling-Else Problem most closely nested rule The else is to be associated with the closest prior if that does not already have an else part bracketing keyword The if statement should be ended with a special keyword if fi Ada provides elsif for nested if. (Compare the followings) if e1 then S1 else if e2 then S2 else if e3 then S3 end if ; end if ; end if; if e1 then S1 elsif e2 then S2 elsif e3 then S3 end if ; Programming Languages 13
Case- and Switch-Statements A kind of Guarded If where the guards are ordinal values. Switch Statements in C falls through semantics each case value should be computed into a single constant in compile-time Case Statements in Ada case values may be grouped (i.e. case values can be listed using vertical bars and subranges) case values must be exhaustive (more safe) Case Expressions in ML the case construct should return a value (because it is an expression) the cases are patterns (the default case may be represented using the wildcard pattern) Programming Languages 14
Guarded Do Due to E. W. Dijkstra The statement is repeated until all the guards are false. do B 1 -> S 1 B 2 -> S 2... When one of B i, say B k, is true, then the S k is executed. B n -> S n od Programming Languages 15
While Loop A guarded do with only one guard. The do-while loop is a syntactic sugar of while. do S while (e); S; while (e) S; Multiple termination points can be made using the break statement (cf. continue statement) Programming Languages 16
For Loop Implements the counter controlled repetition Good for array processing Note) ISO Standard C The scope of the counter variable (index variable) is generally limited to the inside of the loop Some restrictions may be imposed on the index variable, say i, for the optimization of the loop: i cannot be changed within the loop body. i is undefined after the loop terminates. i must be of restricted type and cannot be declared in other ways. Programming Languages 17
Design Issues of the For Loops Are the loop bounds evaluated only once? Should the loop body be executed when the lower bound is greater than the upper bound? Is it possible to exit the loop early? (exit or break statement) What restrictions should be imposed on the index variable? Programming Languages 18
Iterator Iterator in CLU provides a general form of for-loop constructs similar to a history-sensitive function adopted by some object-oriented languages as iterator objects... for c: char in stringchars(s) do... stringchars = iter (s: string) yields (char); index: int := 1; limit: int := string$size(s); while index <= limit do yield (string$fetch(s, index)) index := index + 1; end; end stringchars; The iterator stringchars yields each character from the argument string. Programming Languages 19
Spaghetti Code due to GOTO Compare the following codes. IF (X.GT.0) GOTO 10 IF (X.LT.0) GOTO 20 X = 1 GOTO 30 10 X = X + 1 GOTO 30 20 X = -X GOTO 10 30 CONTINUE if (x > 0) x = x + 1; else if (x < 0) { x = -x; x = x + 1; } else x = 1; Programming Languages 20
Theoretical Foundation Theoretical Foundation on Structured Control Böhm and Jacopini, 1996 Every possible control structure could be expressed using structured control constructs: sequence structures selection structures repetition structures Programming Languages 21
The GOTO Controversy GO TO Statement Considered Harmful Dijkstra, 1968 GOTO considered harmful considered harmful Rubin, 1987 As a result Significant restrictions are imposed on the use of GOTO. Java replaces GOTO with labeled break and labeled continue. Java makes goto into a reserved word. Programming Languages 22
Exception Handling Properties of Exceptions Implicit Control Structure: There is no syntactic indication for the transfer of control. Preemptive Control Structure: The normal program control is interrupted to handle exceptional cases. Kinds of Exceptions Asynchronous Exceptions occur at any moment hardware failure, communication failure Synchronous Exceptions occur in direct response to actions by the program file-open failure, divide-by-zero Programming Languages 23
Exception Handling Scenario normal control flow unusual event raise or throw exception handler Programming Languages 24
Design Issues of Exception Handling Exceptions What exceptions are predefined? Can they be disabled? Can user-defined exceptions be created? What is the scope of exceptions? Handlers How are handlers defined? What default handlers are provided? Can the predefined handlers be replaced? Control How is the control passed to a handler? Where does the control pass after the handler is executed? What run-time environment remains after the handler executes? Programming Languages 25
Exceptions (Language Examples) Exception Declaration Additional Data of Exceptions Scope Rule ML allowed allowed Ada allowed not allowed the same scope rule as other declarations C++ not allowed but any type can be an exception allowed Programming Languages 26
Handlers (Language Examples) C++ Ada ML Handler Syntax try { } catch (type1 var1){ } catch (type2 var2){ } begin exception when exception1 => when exception2 => val name = handle exception1 => exception2 => Redefining the Default Handlers allowed not allowed but can be disabled not allowed Programming Languages 27
Control Exception Raise system-defined exceptions: automatically raised, may be manually raised user-defined exceptions: manually raised only Exception Propagation If no handlers found, then the handler section of the enclosing block is consulted If no handlers found until the outermost block is reached, then the default handler is called Return from Handler Resumption Model: the control is returned back to the point where the exception was first raised. Termination Model: the control is transferred to the code following the executed handler. (mostly used) Programming Languages 28
Exception Specification Exception Specification a list of exceptions attached to a subprogram the subprogram can raise only those exceptions in the exception specification Advantages of Exception Specification the compiler can perform some optimization using this information the compiler can identify the needless handlers Exception Handling Example See Fig. 7.11 (Recursive Descent Calculator in C++) Programming Languages 29