chapter 7 control i expressions and...

29
Chapter 7 Control IExpressions and Statements Expressions Conditional Statements and Guards Loops and Variation on WHILE The GOTO Controversy Exception Handling

Upload: dangtruc

Post on 24-May-2018

232 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: Chapter 7 Control I Expressions and Statementscompiler.sangji.ac.kr/lecture/plt/2006_2/PLT_ch07_ENG.pdf · Chapter 7 Control I—Expressions and Statements ... – single-entry, single-exit

Chapter 7Control I—Expressions and Statements

ExpressionsConditional Statements and GuardsLoops and Variation on WHILEThe GOTO ControversyException Handling

Page 2: Chapter 7 Control I Expressions and Statementscompiler.sangji.ac.kr/lecture/plt/2006_2/PLT_ch07_ENG.pdf · Chapter 7 Control I—Expressions and Statements ... – single-entry, single-exit

Programming Languages 2

Values and EffectsImportant Concepts in Programming Languages

Complicating Factors– expressions with side effects– functions with side effects

Values

Expressions

Functions

Effects

Statements

Procedures subprograms

Page 3: Chapter 7 Control I Expressions and Statementscompiler.sangji.ac.kr/lecture/plt/2006_2/PLT_ch07_ENG.pdf · Chapter 7 Control I—Expressions and Statements ... – single-entry, single-exit

Programming Languages 3

Control StructuresImplicit 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

Page 4: Chapter 7 Control I Expressions and Statementscompiler.sangji.ac.kr/lecture/plt/2006_2/PLT_ch07_ENG.pdf · Chapter 7 Control I—Expressions and Statements ... – single-entry, single-exit

Programming Languages 4

ExpressionsExpressions 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

Page 5: Chapter 7 Control I Expressions and Statementscompiler.sangji.ac.kr/lecture/plt/2006_2/PLT_ch07_ENG.pdf · Chapter 7 Control I—Expressions and Statements ... – single-entry, single-exit

Programming Languages 5

Evaluation Order of ExpressionsApplicative 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

Page 6: Chapter 7 Control I Expressions and Statementscompiler.sangji.ac.kr/lecture/plt/2006_2/PLT_ch07_ENG.pdf · Chapter 7 Control I—Expressions and Statements ... – single-entry, single-exit

Programming Languages 6

Applicative Order Example

In most languages, the evaluation order of operands (or the arguments) is not specified.

(3+4)*(5-6)

7*(5-6)

7*-1

(3+4)*-1

-7

Page 7: Chapter 7 Control I Expressions and Statementscompiler.sangji.ac.kr/lecture/plt/2006_2/PLT_ch07_ENG.pdf · Chapter 7 Control I—Expressions and Statements ... – single-entry, single-exit

Programming Languages 7

Evaluation Order and Side-EffectsWhen 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;

}

Page 8: Chapter 7 Control I Expressions and Statementscompiler.sangji.ac.kr/lecture/plt/2006_2/PLT_ch07_ENG.pdf · Chapter 7 Control I—Expressions and Statements ... – single-entry, single-exit

Programming Languages 8

Evaluation Order Specified OperatorsSequence Operators

x = (y+1,x+y,x+1)

Logical And and Logical Or– logical binary operators may be short-circuited

If Expressionsc ? e1 : e2

Case Expressionscase e0 of

a => e1 |b => e2 |c => e3 ;

Page 9: Chapter 7 Control I Expressions and Statementscompiler.sangji.ac.kr/lecture/plt/2006_2/PLT_ch07_ENG.pdf · Chapter 7 Control I—Expressions and Statements ... – single-entry, single-exit

Programming Languages 9

Short-Circuit EvaluationThe short-circuit evaluation enables compact notations– with the short-circuit evaluation

if (x != 0 && y%x == 1) ...

– without the short-circuit evaluationif (x != 0) if (y%x == 1) ...

Some languages support the both kinds of Boolean operators– In Ada,

• and, or not short-circuited• and then, or else short-circuited

Page 10: Chapter 7 Control I Expressions and Statementscompiler.sangji.ac.kr/lecture/plt/2006_2/PLT_ch07_ENG.pdf · Chapter 7 Control I—Expressions and Statements ... – single-entry, single-exit

Programming Languages 10

Normal Order EvaluationThe 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)

4*double(2)

4*(2+2)

4*4

16

double(2)*(2+2)

double(2)*4

(2+2)*4

Page 11: Chapter 7 Control I Expressions and Statementscompiler.sangji.ac.kr/lecture/plt/2006_2/PLT_ch07_ENG.pdf · Chapter 7 Control I—Expressions and Statements ... – single-entry, single-exit

Programming Languages 11

Conditional StatementsIn 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

Page 12: Chapter 7 Control I Expressions and Statementscompiler.sangji.ac.kr/lecture/plt/2006_2/PLT_ch07_ENG.pdf · Chapter 7 Control I—Expressions and Statements ... – single-entry, single-exit

Programming Languages 12

Guarded IfDue to E. W. DijkstraNondeterministic selection of statements

if B1 -> S1| B2 -> S2...

| Bn -> Snfi

When one of Bi, say Bk, is true,then the Sk is executed.

Page 13: Chapter 7 Control I Expressions and Statementscompiler.sangji.ac.kr/lecture/plt/2006_2/PLT_ch07_ENG.pdf · Chapter 7 Control I—Expressions and Statements ... – single-entry, single-exit

Programming Languages 13

Dangling-Else ProblemWhich 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 keywordif … 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 S1elsif e2 then S2 elsif e3 then S3 end if ;

Page 14: Chapter 7 Control I Expressions and Statementscompiler.sangji.ac.kr/lecture/plt/2006_2/PLT_ch07_ENG.pdf · Chapter 7 Control I—Expressions and Statements ... – single-entry, single-exit

Programming Languages 14

Case- and Switch-StatementsA 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-timeCase 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)

Page 15: Chapter 7 Control I Expressions and Statementscompiler.sangji.ac.kr/lecture/plt/2006_2/PLT_ch07_ENG.pdf · Chapter 7 Control I—Expressions and Statements ... – single-entry, single-exit

Programming Languages 15

Guarded DoDue to E. W. DijkstraThe statement is repeated until all the guards are false.

do B1 -> S1| B2 -> S2...

| Bn -> Snod

When one of Bi, say Bk, is true,then the Sk is executed.

Page 16: Chapter 7 Control I Expressions and Statementscompiler.sangji.ac.kr/lecture/plt/2006_2/PLT_ch07_ENG.pdf · Chapter 7 Control I—Expressions and Statements ... – single-entry, single-exit

Programming Languages 16

While LoopA 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)

Page 17: Chapter 7 Control I Expressions and Statementscompiler.sangji.ac.kr/lecture/plt/2006_2/PLT_ch07_ENG.pdf · Chapter 7 Control I—Expressions and Statements ... – single-entry, single-exit

Programming Languages 17

For LoopImplements the counter controlled repetitionGood for array processingNote) ISO Standard CThe scope of the counter variable (index variable) is generally limited to the inside of the loopSome 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.

Page 18: Chapter 7 Control I Expressions and Statementscompiler.sangji.ac.kr/lecture/plt/2006_2/PLT_ch07_ENG.pdf · Chapter 7 Control I—Expressions and Statements ... – single-entry, single-exit

Programming Languages 18

Design Issues of the For LoopsAre 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?

Page 19: Chapter 7 Control I Expressions and Statementscompiler.sangji.ac.kr/lecture/plt/2006_2/PLT_ch07_ENG.pdf · Chapter 7 Control I—Expressions and Statements ... – single-entry, single-exit

Programming Languages 19

IteratorIterator 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.

Page 20: Chapter 7 Control I Expressions and Statementscompiler.sangji.ac.kr/lecture/plt/2006_2/PLT_ch07_ENG.pdf · Chapter 7 Control I—Expressions and Statements ... – single-entry, single-exit

Programming Languages 20

“Spaghetti” Code due to GOTOCompare the following codes.

IF (X.GT.0) GOTO 10IF (X.LT.0) GOTO 20X = 1GOTO 30

10 X = X + 1GOTO 30

20 X = -XGOTO 10

30 CONTINUE

if (x > 0)x = x + 1;

else if (x < 0){ x = -x;

x = x + 1;}else

x = 1;

Page 21: Chapter 7 Control I Expressions and Statementscompiler.sangji.ac.kr/lecture/plt/2006_2/PLT_ch07_ENG.pdf · Chapter 7 Control I—Expressions and Statements ... – single-entry, single-exit

Programming Languages 21

Theoretical FoundationTheoretical 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

Page 22: Chapter 7 Control I Expressions and Statementscompiler.sangji.ac.kr/lecture/plt/2006_2/PLT_ch07_ENG.pdf · Chapter 7 Control I—Expressions and Statements ... – single-entry, single-exit

Programming Languages 22

The GOTO Controversy“GO TO Statement Considered Harmful”

— Dijkstra, 1968“‘GOTO considered harmful’ considered harmful”

— Rubin, 1987As 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.

Page 23: Chapter 7 Control I Expressions and Statementscompiler.sangji.ac.kr/lecture/plt/2006_2/PLT_ch07_ENG.pdf · Chapter 7 Control I—Expressions and Statements ... – single-entry, single-exit

Programming Languages 23

Exception HandlingProperties 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

Page 24: Chapter 7 Control I Expressions and Statementscompiler.sangji.ac.kr/lecture/plt/2006_2/PLT_ch07_ENG.pdf · Chapter 7 Control I—Expressions and Statements ... – single-entry, single-exit

Programming Languages 24

Exception Handling Scenario

normal control flow

unusualevent

exception

handler

raise or throw

Page 25: Chapter 7 Control I Expressions and Statementscompiler.sangji.ac.kr/lecture/plt/2006_2/PLT_ch07_ENG.pdf · Chapter 7 Control I—Expressions and Statements ... – single-entry, single-exit

Programming Languages 25

Design Issues of Exception HandlingExceptions– 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?

Page 26: Chapter 7 Control I Expressions and Statementscompiler.sangji.ac.kr/lecture/plt/2006_2/PLT_ch07_ENG.pdf · Chapter 7 Control I—Expressions and Statements ... – single-entry, single-exit

Programming Languages 26

Exceptions (Language Examples)

≈ allowednot allowed but

any type can be an exception

C++

not allowedallowedAdathe same scope

rule as other declarations

allowedallowedML

Scope RuleAdditional Data of Exceptions

Exception Declaration

Page 27: Chapter 7 Control I Expressions and Statementscompiler.sangji.ac.kr/lecture/plt/2006_2/PLT_ch07_ENG.pdf · Chapter 7 Control I—Expressions and Statements ... – single-entry, single-exit

Programming Languages 27

Handlers (Language Examples)

not allowed

val name =…

handleexception1 => …exception2 => …

ML

not allowedbut can be disabled

begin…

exceptionwhen exception1 => …when exception2 => …

Ada

allowed

try {…

}catch (type1 var1){…}catch (type2 var2){…}

C++

Redefining the Default HandlersHandler Syntax

Page 28: Chapter 7 Control I Expressions and Statementscompiler.sangji.ac.kr/lecture/plt/2006_2/PLT_ch07_ENG.pdf · Chapter 7 Control I—Expressions and Statements ... – single-entry, single-exit

Programming Languages 28

ControlException 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 calledReturn 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)

Page 29: Chapter 7 Control I Expressions and Statementscompiler.sangji.ac.kr/lecture/plt/2006_2/PLT_ch07_ENG.pdf · Chapter 7 Control I—Expressions and Statements ... – single-entry, single-exit

Programming Languages 29

Exception SpecificationException 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++)