statements (control structures)popl/nykyinen/lecture-slides-pdf-2016/08-control.pdf · statements...

29
Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen TUT Pervasive Computing 1 Statements (control structures) Primitive statements – assignment subprogram call empty statement Compound statement Control structures selection statements iterative statements How to separate statements from each other carriage return terminates each statement (Fortran) a special character separates statements (Pascal) a special character termina- tes each statement (Ada, C) Generators (Python)

Upload: dangduong

Post on 21-Apr-2018

227 views

Category:

Documents


4 download

TRANSCRIPT

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 1

Statements (control structures)

• Primitive statements– assignment– subprogram call– empty statement

• Compound statement• Control structures

– selection statements– iterative statements

• How to separatestatements from eachother– carriage return terminates

each statement (Fortran)– a special character separates

statements (Pascal)– a special character termina-

tes each statement (Ada, C)

Generators (Python)

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 2

Structured programming• Backgrounds

– statements executed one after another– moves in control flow done with goto statement– Dijkstra: ”Go to statement considered harmful” (1968)

• Control structures– each structure has a single entry point and a single exit

point– eliminates the ”come from” problem

• Restrictions for goto statement– the scope of the label can be restricted– jumps into a structure forbidden– exit from a loop (exit, break)

goto included:Fortran, Cobol,PL/I, Ada, C,C++, C#

no goto:Modula-2, Clu,Eiffel, Java

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 3

How many control structures areneeded in a language?

• 1:– conditional jump [goto-statement]

• 2:– selection statement [if-statement]– logically controlled iteration [while-statement]

• Many languages have more control structures– to improve readability and writeability of programs– however, programmers tend to learn only a subset of a

large language

IF expr GOTO label

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 4

Compoundstatement

• Statement sequence surrounded by matchedbraces– begin ... end or { ... }– braces are not necessarily needed

• e.g. Modula-2 (braces integrated tocontrol structures)

• Block– variable and other declarations allowed inside a

compound statement

WHILE expr DO...

END

IF expr THEN ...ELSIF ...ELSE ...END

Modula-2:

IF A < B GOTO 20... else-branchGOTO 30

20:... then-branch

30:

Selection withoutcompound statement(Basic-code):

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing5

Selection statements• 1-way selection (Fortran IV)

• 2-way selection (Algol60)• Multiway selection (e.g. Ada)

IF ( expr ) stmt IF ( FLAG .NE. 1 ) GO TO 20I = 1J = 220 CONTINUE

if expr thenstatement

elsestatementif ( x < 10 ) then size = ”tiny”;

elsif ( x < 100 ) then size = ”small”;elsif ( x < 1000 ) then size = ”large”;else size = ”huge”;end if;

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 6

Selection statements in programminglanguages

if ( sum == 0 )if ( count == 0 )

result = 0;else

result = 1;

if ( sum == 0) {if ( count = 0 ) {

result := 0;}else {

result := 1;}

}

if sum = 0 thenif count = 0 then

result := 0;end if;

elseresult := 1;

end if;

C, Pascal, Java:dangling else+ semantic rule

Perl:compoundstatementforced bythe syntax

Ada:comb-likestructure

Attachingelse-branchto the outerselection:

if ( sum == 0 ) {if ( count == 0 )

result = 0;}else

result = 1;

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 7

Early multiple selectors(in Fortran)

• Arithmetic if– 3-way selector

• Computed goto

IF ( expr ) N1, N2, N3

IF ( expr ) 10, 20, 3010: ...

...GOTO 40

20: ......GOTO 40

30: ......

40:GO TO ( N1, N2, ..., NN ), expr

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 8

Multiple selectors (case)• Conditional statements based on equality

– case label (possible values of the condition)

• Design issues:– What is the type of the selection expression?– What are the values to be selected?

• constants• enumerated values• mutually exclusive

– How to cover all possible values?• default, else, others -branches

case E ofL1: S1;L2: S2;...Ln: Sn;

end

switch ( E ) {case L1: S1;case L2: S2; break;...case Ln: Sn;

}

Pascal-code:

C-code:

Variant recordoptions

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 9

Implementation of selectionstatements

• Compiling if-statement is straightforward– branching is based on the truth value of the condition

(conditional branch)• case-statement (choices for implementation):

– small number of case labels• compiled like a if-then-elsif structure

– medium number of case labels that cover the range atleast nearly totally

• jump address table• empty alternatives: jump to error routine or to the default action

– large number of case labels, large range• hash table or other dictionary

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 10

Implementation ofselection

r1 := Ar2 := Br1 := r1 > r2r2 := Cr3 := Dr2 := r2 > r3r1 := r1 & r2if r1 = 0 goto L2

L1: then_clausegoto L3

L2: else_clauseL3:

if ( ( A > B ) and ( C > D ) ) thenthen_clause

elseelse_clause

Pascal-code:

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 11

Jump address table• Each case label corresponds to an index• Index contains an address where to jump

whenever the condition (E) evaluates equalto the case label

• Address points to code corresponding thebranch case E of

1: S1;2: S2;3: S3;4: S4;

end

1234

...S1S2S3S4...

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

Peculiarities of selection

• Pattern matching in functional languages

• Smalltalk boolean objects− predefined Boolean objects: true and false− method ifTrue:ifFalse:

• two code blocks as parameters representing the”then” and ”else” brances

fact 0 = 1fact n = n * fact ( n – 1 )

total = 0ifTrue: [ average <- 0 ]ifFalse: [ average <- sum // total ]

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 13

Iterative statement

• Definite iteration [counter-controlled loop]– number of iterations is known before-hand

• Indefinite iteration [logically controlled loop]– number of iterations is computed during the iteration– loop completion test either before loop body or after it

loop-- statementsexit when expr;-- statements

end loop;

generalized loopcompletion test (Ada):

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 14

Definite iteration

• Includes a loop variable (counter, index)

• Semantic variations in programming languages:– What is the value of the loop variable after the loop?– Can the loop variable be changed within the loop?– Are the upper and lower bounds (expr1 and expr2) be

evaluated only once, or once for every iteration?

Passingthroughan array

for index from expr1 to expr2 do stmt end

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 15

Definite iteration in languagesfor index := init_value ( to | downto ) final_value do stmtPascal:

for index in [ reverse ] discrete_range loopstmts

end loop; i: Float := 3.14;for i in 1..10 loop

sum := sum + i;end loop;

Ada:

The scope of theloop counter in Ada:

FOR index := init_value TO final_value [ BY step_value ] DOstmts

END

Modula-2:

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 16

for-statement in Cfor ( index = 0; index <= 10; index++ )

sum += list [ index ];

• No actual loop counter– the values of variables in the expressions can be

changed in the loop• Includes three expressions

– each expression can be missing– each expression can be compound

for ( count1 = 0, count2 = 1.0;count1 <= 10 && count2 <= 100.0;sum = ++count1 + count2, count2 *= 2.5 );

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 17

for-statements in C++ and Java

• C++– ”loop counter” declared inside the loop

• no effect on visibility

• Java– condition must be truth value– ”loop counter” is visible only inside the loop

for ( int i = 0; i < MAX; i++ )

int i;for ( i = 0; i < MAX; i++ )

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 18

for-statement in Algol60<for_stmt> ::= for <var> := <list_elem> {, <list_elem>} do <stmt><list_elem> ::= <expr>

| <expr> step <expr> until <expr>| <expr> while <bool_expr>

for index := 1, 4, 13,41 step 2 until 47,3 * index while index < 1000,34, 2, -24 do

sum := sum + index

1, 4, 13,41, 43, 45, 47,147, 441,34, 2, -24

Grammar:

Different(or same)uses:

Compli-cateduse:

for count := 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 dolist [ count ] := 0

for count := 1 step 1 until 10 dolist [ count ] := 0

for count := 1, count + 1 while ( count <= 10 ) dolist [ count ] := 0

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 19

for-statementin Algol60(an example)

i := 1;for count := 1 step count until 3 * i do

i := i + 1

i count step until1 1 1 32 2 2 63 4 4 94 8 8 125 16 16 15loop termination

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 20

Value of the counter after the loop

• Safe solution:– loop counter is not visible after the loop

• If loop counter is visible:– value is undefined

• e.g. Pascal– value is the latest value assigned (the next value over

the upper bound)• e.g. Fortran, Algol60 var c: ’a’..’z’;

...for c := ’a’ to ’z’ do begin

...end;

Pascal-code:

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 21

Indefinite iteration

• Location of the loop completion test– before the loop body

• loop is executed 0-n times

– after the loop body• loop is executed 1-n times

• Logic of the completion test– while: continue if true– until: end if true

sum := 0;Read ( num );while num >= 0 do begin

sum := sum + num;Read ( num );

end;

sum := 0;num := 0;repeat

sum := sum + num;Read ( num );

until num < 0;

Pascal-code:

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 22

Special iterations• Hybrid between definite and indefinite

iteration (for-statement in C)for ( E1; E2; E3 ) S; Û E1; while ( E2 ) { S; E3 };

• One general structure that can be specialized(Algol68)– mandatory parts : do and od

for index from expr1 by expr2 to expr3while expr4 do statement od

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

Smalltalk iteration

• Conditional block: returns either true orfalse

• Class Block provides method whileTrue:,which has a block (statements to beiterated) as its parameter

count <- 1.sum <- 0.[ count <= 20 ]

whileTrue: [ sum <- sum + count.count <- count + 1 ]

Conditional block

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 24

Loop controlOUTER_LOOP:for row in 1..max_rows loop

INNER_LOOP:for col in 1..max_cols loop

sum := sum + mat ( row, col );exit OUTER_LOOP when sum > 1000;

end loop INNER_LOOP;end loop OUTER_LOOP;

while ( sum < 1000 ) {getnext ( value );if ( value < 0 ) continue;sum += value;

}

while ( sum < 1000 ) {getnext ( value );if ( value < 0 ) break;sum += value;

}

Ada:

C andC++:

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 25

Loops and data structurestype Days is ( Mon, Tue, Wed, Thu, Fri, Sat, Sun );for Index in Days loop ... end loop;

int[ ] tbl = { 1, 2, 3 };for ( int i : tbl ) { … }

String [ ] strList = { ”Bob”, ”Carol”, ”Ted” };foreach ( String name in strList )

Console.WriteLine ( ”Name: ”, name );

Ada:

Java:

C#:

Haskell: Lambdas and library functions used as loops:

let tbl = [ 1, 2, 3 ] inmap ( \x -> x * x + 1 ) tbl

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 26

Guarded commands

if <bool_expr> -> <stmt>[ ] <bool_expr> -> <stmt>[ ] <bool_expr> -> <stmt>fi

if i = 0 -> sum := sum + i[ ] i > j -> sum := sum + j[ ] j > i -> sum := sum + ifi

if x >= y -> max := x[ ] y >= x -> max := yfi

Syntax in selection: Use in selection:

=> run time error, if i = j ≠ 0

Dijkstra’s proposalfor a safe selectionstructure(expressed insyntax of Algol68)

do expr1 -> stmt1[ ] expr2 -> stmt2[ ] ...[ ] exprN -> stmtNod

Use in iteration:

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

Generators (Python)• Functions are ”single-use”: parameters in, return

value out• Generators are ”multi-use”: they can produce

multiple values (when needed)• Generator is an iterator, which is used to access

(and calculate) the values• Generator functions return generators (iterators)• (Or: normal data structures can be viewed as

generator functions with pre-calculated values,accessed through iterators) Generator functions

Generator expressions

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

Example of generatorsdef firstn ( n ):

num = 0while num < n:

yield num # ”return”, ready to continuenum += 1

i = firstn ( 10 )print ( next ( i ) )print ( next ( i ) )j = ( x * x for x in i )print ( next ( j ) )

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

Benefits of generators

• Avoid creating big data structures, createvalues when necessary

• Allow lazy evaluation (almost)• Allow pipeline programming: actions

(generators) are chained together, feedingvalues to next action (generator)