CSE 452 Programming Languages Control Flow Outline u

  • Slides: 42
Download presentation
CSE 452: Programming Languages Control Flow

CSE 452: Programming Languages Control Flow

Outline u Control Structures l Selection Statements l Iterative Statements l Unconditional Branches u

Outline u Control Structures l Selection Statements l Iterative Statements l Unconditional Branches u Subprograms and Procedures Organization of Programming Languages-Cheng (Fall 2004) 2

Iterative Statements u Repeated execution of a statement or compound statement l accomplished either

Iterative Statements u Repeated execution of a statement or compound statement l accomplished either by iteration or recursion; l here we look at iteration, because recursion is a unitlevel control (e. g. , using functions) u General design issues for iteration control statements: 1. How is the iteration controlled? v 2. Counter-controlled vs logical-controlled Where should the control mechanism appear in the loop? v pretest (before loop body is executed) vs posttest (after loop body is executed) Organization of Programming Languages-Cheng (Fall 2004) 3

Iterative Statements u Counter-Controlled Loops for (i = init_value; i < terminal_value; i+=stepsize) {

Iterative Statements u Counter-Controlled Loops for (i = init_value; i < terminal_value; i+=stepsize) { … } l Loop variable Loop parameters Design Issues: 1. 2. 3. 4. What are the type and scope of the loop variable? What is the value of the loop variable at loop termination? Should it be legal for the loop variable or loop parameters to be changed in the loop body, and if so, does the change affect loop control? Should the loop parameters be evaluated only once, or once for every iteration? Organization of Programming Languages-Cheng (Fall 2004) 4

Counter-Controlled Loops u FORTRAN 95 l Syntax: Do label u u u var =

Counter-Controlled Loops u FORTRAN 95 l Syntax: Do label u u u var = initial, terminal [, stepsize] stepsize can be any value but zero parameters can be expressions Design choices: 1. Loop var must be integer; loop parameters can be expressions 2. The loop var cannot be changed in the loop, but loop parameters can because they are evaluated only once, it does not affect loop control 3. Single entry structure – loop can be entered through Do statement Organization of Programming Languages-Cheng (Fall 2004) 5

Counter-Controlled Loops u Fortran 95: Do label var = init_expression, terminal_expression [, step_expression] Operational

Counter-Controlled Loops u Fortran 95: Do label var = init_expression, terminal_expression [, step_expression] Operational Semantics for Fortran 95 Do statement init_value = init_expression terminal_value = terminal_expression step_value = step_expression do_var = init_value iteration_count = max(int((terminal_value– init_value+step_value)/step_value), 0) loop: if iteration_count 0 goto out [loop body] do_var = do_var + step_value iteration_count = interation_count – 1 goto loop out: … Organization of Programming Languages-Cheng (Fall 2004) 6

Counter-Controlled Loops u Another form of Do statement for FORTRAN 95 [name: ] DO

Counter-Controlled Loops u Another form of Do statement for FORTRAN 95 [name: ] DO variable = initial, terminal [, stepsize] … END DO [name] u Uses a special word for closing: END DO Organization of Programming Languages-Cheng (Fall 2004) 7

Counter-Controlled Loops u Ada l Syntax: for var in [reverse] discrete_range loop . .

Counter-Controlled Loops u Ada l Syntax: for var in [reverse] discrete_range loop . . . end loop; l l reverse indicates that values of discrete range are assigned in reverse order Step size is always one (or next element in discrete_range) Organization of Programming Languages-Cheng (Fall 2004) 8

Counter-Controlled Loops u Ada Design choices: 1. Type of the loop var is that

Counter-Controlled Loops u Ada Design choices: 1. Type of the loop var is that of the discrete range ð 2. discrete range is subrange of integer or enumeration type, such as 1. . 10 or Monday. . Friday Scope of loop var is the loop body (it is implicitly declared); loop var does not exist outside the loop Count : Float : = 1. 35; for Count in 1. . 10 loop Sum : = Sum + Count; end loop; … Count gets the value of 1. 35 3. 4. The loop var cannot be changed in the loop, but the discrete range can; it does not affect loop control The discrete range is evaluated just once Organization of Programming Languages-Cheng (Fall 2004) 9

Counter-Controlled Loops u C-based languages l Syntax: for ([expr_1] ; [expr_2] ; [expr_3]) loop

Counter-Controlled Loops u C-based languages l Syntax: for ([expr_1] ; [expr_2] ; [expr_3]) loop body l Loop body can be single, compound, or null statement l Expressions can be whole statements, or even statement sequences, with the statements separated by commas l The value of a multiple-statement expression is the value of the last statement in the expression for (i = 0, j = 10; j == i; … l i++) All expressions of C’s for statement are optional u If expr_2 is absent, it is an infinite loop Organization of Programming Languages-Cheng (Fall 2004) 10

Counter-Controlled Loops for ([expr_1] ; [expr_2] ; [expr_3]) loop body u Operational Semantics: expr_1

Counter-Controlled Loops for ([expr_1] ; [expr_2] ; [expr_3]) loop body u Operational Semantics: expr_1 loop: if expr_2 = 0 goto out [loop_body] expr_3 goto loop out: … % initialization (evaluate once) % loop control (each iter) % increment loop counter? Organization of Programming Languages-Cheng (Fall 2004) 11

Counter-Controlled Loops u Design choices for C: 1. There is no explicit loop variable

Counter-Controlled Loops u Design choices for C: 1. There is no explicit loop variable or loop parameters u All involved variables can be changed in the loop body 2. It is legal to branch into loop body 3. The first expression is evaluated once, but the other two are evaluated with each iteration Organization of Programming Languages-Cheng (Fall 2004) 12

Counter-Controlled Loops u C++ l Differs from C in two ways: 1. 2. The

Counter-Controlled Loops u C++ l Differs from C in two ways: 1. 2. The control expression can also be Boolean The initial expression can include variable definitions (scope is from the definition to the end of the loop body) for (int i=0; i < len; i++) { … } u Java l Differs from C++ in that the control expression must be Boolean Organization of Programming Languages-Cheng (Fall 2004) 14

Logically-Controlled Loops u Repetition control is based on a Boolean expression, rather than a

Logically-Controlled Loops u Repetition control is based on a Boolean expression, rather than a counter u More general than counter-controlled loops l Every counting loop can be built with a logical loop, but not vice-versa u Design Issues: 1. Pretest or postest? 2. Should logically controlled loop be a special form of counting loop statement or a separate statement? Organization of Programming Languages-Cheng (Fall 2004) 15

Logically-Controlled Loops u Pascal has separate pretest and posttest logical loop statements (while-do and

Logically-Controlled Loops u Pascal has separate pretest and posttest logical loop statements (while-do and repeat-until) u C and C++ also have both while (count > 0) { … } do { … } while (count > 0); l Legal to branch into both while and do loop bodies Organization of Programming Languages-Cheng (Fall 2004) 16

Logically-Controlled Loops u Ada has a pretest version, but no posttest u FORTRAN 77,

Logically-Controlled Loops u Ada has a pretest version, but no posttest u FORTRAN 77, 90, and 95 have neither u Perl has two pretest logical loops, while and until, but no posttest logical loop while (count > 0) { … } until (count == 0) { … } Organization of Programming Languages-Cheng (Fall 2004) 17

User-Located Loop Control u User modify the control flow of program u Design issues:

User-Located Loop Control u User modify the control flow of program u Design issues: 1. 2. Should the conditional mechanism be an integral part of the exit? Should only one loop body be exited or can enclosing loops also be exited? Organization of Programming Languages-Cheng (Fall 2004) 18

User-Located Loop Control u Exit statement: v Unconditional unlabeled exit: break (C, C++) for

User-Located Loop Control u Exit statement: v Unconditional unlabeled exit: break (C, C++) for (index=0; index<10; index++) { … if (value < 0) break; } v Unconditional labeled exit: break (Java, C#), last (Perl) C#: outer. Loop: for (row=0; row<num. Rows; row++) for (col = 0; col < num. Cols; col++) { sum += matrix[row][col]; if (sum > 1000) break outer. Loop; } Perl: LINE: while (<STDIN>) { last LINE if /^$/; . . . } Organization of Programming Languages-Cheng (Fall 2004) 19

User-Located Loop Control u Skip the rest of loop body: v C/C++ have unlabeled

User-Located Loop Control u Skip the rest of loop body: v C/C++ have unlabeled control statement (continue) while (sum < 1000) { value = get. Next. Value(); if (value < 0) continue; sum += value; } v Java, Perl, and C# have statements similar to continue, except they can include labels that specify which loop is continued Organization of Programming Languages-Cheng (Fall 2004) 20

Iteration Based on Data Structures u Loops are controlled by number of elements in

Iteration Based on Data Structures u Loops are controlled by number of elements in a data structure l Perl, Javascript, PHP, and C# have such statements Perl: @values = (1, 2, 3, 4, 5); foreach $value (@values) { print “Value is $valuen”; } C#: }; String[] str. List = {“Bob”, “John”, “Carol” foreach (String name in str. List) … Organization of Programming Languages-Cheng (Fall 2004) 21

Iteration Based on Data Structures u More general approach l uses a user-defined data

Iteration Based on Data Structures u More general approach l uses a user-defined data structure and a userdefined function (called an iterator) to go through the structure’s elements l Java has a Collection interface that contains two methods: boolean add(Object obj) - adds elements to collection Iterator iterator() - used to visit the elements in the collection one by one. Organization of Programming Languages-Cheng (Fall 2004) 22

Unconditional Branching u Transfers execution control to a specified location in the program goto

Unconditional Branching u Transfers execution control to a specified location in the program goto label u u u Problem: readability l Some languages do not have them: e. g. , Java Loop exit statements are restricted and somewhat camouflaged goto’s Label forms: 1. Unsigned int constants: Pascal (with colon) FORTRAN (no colon) 2. Identifiers with colons: ALGOL 60, C 3. Variables as labels: PL/I Organization of Programming Languages-Cheng (Fall 2004) 23

Subprograms u Two fundamental abstraction facilities in programming language: l Process abstraction – represented

Subprograms u Two fundamental abstraction facilities in programming language: l Process abstraction – represented by subprograms l Data abstraction u General characteristics of subprograms: 1. A subprogram has a single entry point 2. The caller is suspended during execution of the called subprogram 3. Control always returns to the caller when the called subprogram’s execution terminates Organization of Programming Languages-Cheng (Fall 2004) 24

Subprograms u A subprogram definition is a description of the actions of the subprogram

Subprograms u A subprogram definition is a description of the actions of the subprogram abstraction u A subprogram call is an explicit request that the subprogram be executed l A subprogram is active if, after being called, it has begun execution but has not yet completed that execution A subprogram header is the first line of the definition l Specifies that the following syntactic unit is a subprogram of some particular kind - using a special word (function, procedure, etc) l Provides name of subprogram u l Specifies the list of formal parameters Fortran: Subroutine Adder(parameters) Ada: procedure Adder(parameters) Organization of Programming Languages-Cheng (Fall 2004) 25

Subprograms u The parameter profile (signature) of a subprogram is the number, order, and

Subprograms u The parameter profile (signature) of a subprogram is the number, order, and types of its parameters u The protocol of a subprogram is its parameter profile plus, if it is a function, its return type u Subprograms can have declarations as well as definitions u Subprogram declaration provides the subprogram’s protocol but do not include their bodies l Function declarations in C/C++ are called prototypes Organization of Programming Languages-Cheng (Fall 2004) 26

Parameters u A formal parameter is a dummy variable listed in subprogram header and

Parameters u A formal parameter is a dummy variable listed in subprogram header and used in the subprogram the u An actual parameter represents a value or address used in the subprogram call statement void do. Nothing (int formal_param) { … } main() { int actual_param; do. Nothing(actual_param); } Organization of Programming Languages-Cheng (Fall 2004) 27

Parameters u Actual/Formal Parameter Correspondence l Binding of actual to formal parameters 1. Positional

Parameters u Actual/Formal Parameter Correspondence l Binding of actual to formal parameters 1. Positional parameters v 2. First actual param bound to first formal param, etc Keyword parameters v Name of formal param to which actual param is bound is specified with actual param Ada: Sumer( Length => My_Length, List => My_Array, Sum => My_Sum ); v Advantage: order is irrelevant Disadvantage: user must know the formal parameter’s names v Organization of Programming Languages-Cheng (Fall 2004) 28

Parameters u Default values of formal parameters l Allowed by C++, Fortran 95, Ada

Parameters u Default values of formal parameters l Allowed by C++, Fortran 95, Ada and PHP l Default value is used if no actual parameter is passed to the formal parameter Ada: function Compute_Pay( Income : Float; Exemptions : Integer : = 1; Tax_Rate : Float ) return Float pay : = Compute_Pay (20000. 00, Tax_Rate => 0. 15); l C# allows methods to accept variable number of params of the same type public void Display. List(params int[] list ) { foreach (int next. Value in list) { Console. Write. Line(“Next value {0}”, next. Value); } } Organization of Programming Languages-Cheng (Fall 2004) 29

Procedures and Functions u Procedures provide user-defined statements u Functions provide user-defined operators l

Procedures and Functions u Procedures provide user-defined statements u Functions provide user-defined operators l Value produced by function is returned to the calling code, effectively replacing the call itself float power(float base, float exp) result = 3. 4 * power(10. 0, x); u C-based languages l have only functions (but they can behave like procedures) l Can be defined to return no value if the return type is void Organization of Programming Languages-Cheng (Fall 2004) 30

Design Issues for Subprograms 1. 2. 3. 4. 5. 6. 7. 8. 9. What

Design Issues for Subprograms 1. 2. 3. 4. 5. 6. 7. 8. 9. What parameter passing methods are provided? Are parameter types checked? Are local variables static or dynamic? What is the referencing environment of a passed subprogram? Are parameter types in passed subprograms checked? Can subprogram definitions be nested? Can subprograms be overloaded? Are subprograms allowed to be generic? Is separate or independent compilation supported? Organization of Programming Languages-Cheng (Fall 2004) 31

Local Referencing Environments u Local variables: variables defined inside subprograms l their scope is

Local Referencing Environments u Local variables: variables defined inside subprograms l their scope is the body of subprogram in which they are defined u Stack-dynamic: bound to storage when subprogram begins execution, unbound when its execution terminates l 1. 2. 3. u Advantages: Support for recursion Storage for local variables of active subprogram can be shared with local variables of inactive subprograms Disadvantages: Allocation/deallocation time Indirect addressing (indirectness because the place in stack where a particular local variable is stored can only be determined at run time) Subprograms cannot be history sensitive Ø Cannot retain data values of local variables between calls Static: bound to storage at compile-time Organization of Programming Languages-Cheng (Fall 2004) 32

Parameter Passing: Semantic Models u Semantic models formal parameters u In mode – can

Parameter Passing: Semantic Models u Semantic models formal parameters u In mode – can receive data from corresponding actual parameters l Actual value is either copied to caller, or an access path is transmitted u Out mode – can transmit data to actual parameters u Inout mode – can do both receive/transmit data Organization of Programming Languages-Cheng (Fall 2004) 33

Parameter Passing: Implementation u Pass by value (in mode) u u Value of actual

Parameter Passing: Implementation u Pass by value (in mode) u u Value of actual parameter is used to initialize formal parameter, which acts as a local variable void foo (int a) { a = a + 1; } void main() { int b = 2; foo(b); } Normally implemented by copying actual parameter to formal parameter Can also be implemented by transmitting access path to the value of actual parameter as long as cell is write protected Disadvantages: l l Requires more storage (duplicated space) Cost of the moves (if the parameter is large) Organization of Programming Languages-Cheng (Fall 2004) 34

Parameter Passing: Implementation u Pass by result (out mode) l Local’s value is passed

Parameter Passing: Implementation u Pass by result (out mode) l Local’s value is passed back to the caller l No value transmitted to the subprogram l Formal parameter acts as local variable, but just before control is transferred back to caller, its value is transmitted to actual parameter l Disadvantages: 1. If value is copied back (as opposed to access paths), need extra time and space 2. Pass-by-result can create parameter collision e. g. procedure sub 1(y: int, z: int); . . . sub 1(x, x); l Value of x in the caller (Fall depends Organization of Programming Languages-Cheng 2004) on order of assignments at 35

Parameter Passing: Implementation u Pass by value-result (or pass-by-copy) l Combination of pass-by-value and

Parameter Passing: Implementation u Pass by value-result (or pass-by-copy) l Combination of pass-by-value and pass-by-result l Formal parameter acts as local variable in subprogram l Actual parameter is copied to formal parameter at subprogram entry and copied back at subprogram termination l Share disadvantages of pass-by-result and passby-value u Requires multiple storage for parameters u Requires time for copying values u Problems with parameter collision Organization of Programming Languages-Cheng (Fall 2004) 36

Parameter Passing: Implementation u Pass by reference (or pass-by-sharing) l transmits an access path

Parameter Passing: Implementation u Pass by reference (or pass-by-sharing) l transmits an access path (e. g. , address) to the called subprogram l Called subprogram is allowed to access actual parameter in the calling program unit l Advantage: u l passing process is efficient (no copying and no duplicated storage) Disadvantages: Slower accesses to formal parameters due to additional level of indirect addressing u Allows aliasing u void fun (int &first, int &second); … fun(total, total); Organization of Programming Languages-Cheng (Fall 2004) 37

Parameter Passing: Implementation u Pass-by-reference l Collisions aliases due to array elements can also

Parameter Passing: Implementation u Pass-by-reference l Collisions aliases due to array elements can also cause void fun(int &first, int &second) fun(list[i], list[j]); /* where i=j */ void fun 1(int &first, int *a); fun 1(list[i], list); l Collisions between formal parameters and nonlocal variables that are visible int *global; void sub(int *param) { void main() { extern int *global; … … } sub(global); … } Organization of Programming Languages-Cheng (Fall 2004) 38

Parameter Passing: Implementation u Pass by Name l Another type of inout mode l

Parameter Passing: Implementation u Pass by Name l Another type of inout mode l Actual parameter is textually substituted for the corresponding formal parameters u l Advantage: u l Actual binding of value and address is delayed until formal parameter is assigned or referenced flexibility of late binding Disadvantage: u very expensive related to other parameter passing l l Not used in any widely used language Another Example: u Used at compile time by macros, and for generic subprograms in C++ Organization of Programming Languages-Cheng (Fall 2004) 39

Pass-by-value int m=8, i=5; foo(m); print m; # prints 8 # since m is

Pass-by-value int m=8, i=5; foo(m); print m; # prints 8 # since m is passed by-value. . . proc foo (byval b) { b = i + b; # # # b is byval so it is essentially a local variable initialized to 8 (the value of the actual back in the calling environment) the assignment to b cannot change the value of m back in the main program } Organization of Programming Languages-Cheng (Fall 2004) 40

Pass-by-reference int m=8, i=5; foo(m); print m; # prints 13 # since m is

Pass-by-reference int m=8, i=5; foo(m); print m; # prints 13 # since m is passed by-reference. . . proc foo (byref b) { b = i + b; # b is byref so it is a pointer back to the actual # parameter back in the main program (containing 8 initially) # the assignment to b actually changes the value in m back # in the main program # i accesses the variable in the main via scope rules } Organization of Programming Languages-Cheng (Fall 2004) 41

Pass-by-value-result int m=8, i=5; foo(m); print m; # prints 13 # since m is

Pass-by-value-result int m=8, i=5; foo(m); print m; # prints 13 # since m is passed by-value-result. . . proc foo (byvres b) { b = i + b; # # # b is byves so it copies value of the actual parameter (containing 8 initially) new value of b is copied back to actual parameter in the main program i accesses the variable in the main via scope rules } Organization of Programming Languages-Cheng (Fall 2004) 42

Pass-by-name array A [1. . 100] of int; int i=5; foo(A[i], i); print A[i];

Pass-by-name array A [1. . 100] of int; int i=5; foo(A[i], i); print A[i]; # prints A[6]. . . # so prints 7 array A [1. . 100] of int; int i=5; foo(A[i]); print A[i]; # prints A[5]. . . # not sure what # good example proc foo (name B, name k) { k = 6; B = 7; } # a problem here. . . proc foo (name B) { int i = 2; B = 7; } # text substitution does this proc foo { i = 6; A[i] = 7; } proc foo { int i = 2; A[i] = 7; } Organization of Programming Languages-Cheng (Fall 2004) 43