Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 9 Subprograms.

Similar presentations


Presentation on theme: "Chapter 9 Subprograms."— Presentation transcript:

1 Chapter 9 Subprograms

2 Augment Sebesta Material
Programming Languages-Cheng (Fall 2004) Subprograms – parameter passing Runtime Environment Concepts Chapter 7 of Compilers: Principles, Techniques and Tools, Aho, et al., Addison-Wesley

3 Chapter 9 Topics Fundamentals of Subprograms
Design Issues for Subprograms Local Referencing Environments Runtime Environment Parameter-Passing Methods Parameters That Are Subprograms Calling Subprograms Indirectly Design Issues for Functions Overloaded Subprograms Generic Subprograms User-Defined Overloaded Operators Coroutines Copyright © 2015 Pearson. All rights reserved.

4 Introduction Two fundamental abstraction facilities
Process abstraction Emphasized from early days Discussed in this chapter Data abstraction Emphasized in the1980s Discussed at length in Chapter 11 Copyright © 2015 Pearson. All rights reserved.

5 Fundamentals of Subprograms
Each subprogram has a single entry point The calling program is suspended during execution of the called subprogram Control always returns to the caller when the called subprogram’s execution terminates Copyright © 2015 Pearson. All rights reserved.

6 Basic Definitions A subprogram definition describes the interface to and the actions of the subprogram abstraction In Python, function definitions are executable; in all other languages, they are non-executable In Ruby, function definitions can appear either in or outside of class definitions. If outside, they are methods of Object. They can be called without an object, like a function In Lua, all functions are anonymous Copyright © 2015 Pearson. All rights reserved.

7 Basic Definitions A subprogram call is an explicit request that the subprogram be executed A subprogram header is the first part of the definition, including the name, the kind of subprogram, and the formal parameters The parameter profile (aka signature) of a subprogram is the number, order, and types of its parameters The protocol is a subprogram’s parameter profile and, if it is a function, its return type Copyright © 2015 Pearson. All rights reserved.

8 Basic Definitions (continued)
Function declarations in C and C++ are often called prototypes A subprogram declaration provides the protocol, but not the body, of the subprogram A formal parameter is a dummy variable listed in the subprogram header and used in the subprogram An actual parameter represents a value or address used in the subprogram call statement Copyright © 2015 Pearson. All rights reserved.

9 Actual/Formal Parameter Correspondence
Positional The binding of actual parameters to formal parameters is by position: the first actual parameter is bound to the first formal parameter and so forth Safe and effective Keyword The name of the formal parameter to which an actual parameter is to be bound is specified with the actual parameter Advantage: Parameters can appear in any order, thereby avoiding parameter correspondence errors Disadvantage: User must know the formal parameter’s names Copyright © 2015 Pearson. All rights reserved.

10 Keyword parameters example
sumer(length = my_length, list = my_array, sum = my_sum) where definition of sumer has formal parameters length, list, sum. The disadvantage to keyword parameters is that the user of the subpro- gram must know the names of formal parameters. Ada, Fortran 95+ and Python allow keyword and positional parameters can be mixed in a call, as in sumer(my_length, sum = my_sum, list = my_array) Copyright © 2015 Pearson. All rights reserved.

11 Formal Parameter Default Values
In certain languages (e.g., C++, Python, Ruby, PHP), formal parameters can have default values (if no actual parameter is passed) In C++, default parameters must appear last because parameters are positionally associated (no keyword parameters) pay = compute_pay( , tax_rate = 0.15) in Python Variable numbers of parameters C# methods can accept a variable number of parameters as long as they are of the same type—the corresponding formal parameter is an array preceded by params In Ruby, the actual parameters are sent as elements of a hash literal and the corresponding formal parameter is preceded by an asterisk. printf Has variable number of Parameters Copyright © 2015 Pearson. All rights reserved.

12 Variable Numbers of Parameters (continued)
In Python, the actual is a list of values and the corresponding formal parameter is a name with an asterisk In Lua, a variable number of parameters is represented as a formal parameter with three periods; they are accessed with a for statement or with a multiple assignment from the three periods Copyright © 2015 Pearson. All rights reserved.

13 parameter structure of Ruby:
The following example skeletal function definition and call illustrate the parameter structure of Ruby: list = [2, 4, 6, 8] def tester(p1, p2, p3, *p4) . . . end tester('first', mon => 72, tue => 68, wed => 59, *list) Inside tester, the values of its formal parameters are as follows: p1 is 'first' p2 is {mon => 72, tue => 68, wed => 59} p3 is 2 p4 is [4, 6, 8] Python supports parameters that are similar to those of Ruby. Copyright © 2015 Pearson. All rights reserved.

14 Procedures and Functions
There are two categories of subprograms Procedures are collection of statements that define parameterized computations Functions structurally resemble procedures but are semantically modeled on mathematical functions They are expected to produce no side effects In practice, program functions have side effects Copyright © 2015 Pearson. All rights reserved.

15 Design Issues for Subprograms
Are local variables static or dynamic? Can subprogram definitions appear in other subprogram definitions? What parameter passing methods are provided? Are parameter types checked? If subprograms can be passed as parameters and subprograms can be nested, what is the referencing environment of a passed subprogram? Copyright © 2015 Pearson. All rights reserved.

16 Design Issues for Subprograms
Are functional side effects allowed? What types of values can be returned from functions? How many values can be returned from functions? Can subprograms be overloaded? Can subprogram be generic? Copyright © 2015 Pearson. All rights reserved.

17 Local Referencing Environments
Local variables can be stack-dynamic - Advantages Support for recursion Storage for locals is shared among some subprograms Disadvantages Allocation/de-allocation, initialization time Indirect addressing Subprograms cannot be history sensitive Local variables can be static Advantages and disadvantages are the opposite of those for stack-dynamic local variables Copyright © 2015 Pearson. All rights reserved.

18 Local Referencing Environments: Examples
In most contemporary languages, locals are stack dynamic In C-based languages, locals are by default stack dynamic, but can be declared static The methods of C++, Java, Python, and C# only have stack dynamic locals In Lua, all implicitly declared variables are global; local variables are declared with local and are stack dynamic Copyright © 2015 Pearson. All rights reserved.

19 Runtime Environment Prof. Steven A. Demurjian
Computer Science & Engineering Department The University of Connecticut 371 Fairfield Way, Unit 2155 Storrs, CT (860)

20 Basic Definitions and Concepts
Procedure Definition Declaration that has a Name and has a Body If Returns a value, then Function Procedure Definition Contains a Sequence of Identifiers Called the Formal Parameters Procedure Call Contains a List of Arguments passed to the Procedure or the Actual Parameters Information in Program can be Characterized Environment: Maps Name to Storage Loc (l-value) Store: Maps Location to Value it Contains (l-value to an r-value) Environment State Compile Time Run Time Name Storage Value

21 A First Look at Activation Records
Storage Organization for Program Execution Code Referenced by PC Global/Local Variables Static Data Area Stack Contains Set of Activation Records All Active Procedures and Functions Heap for Dynamic Memory Allocation Code Static Data Stack Heap

22 A General Activation Record
To the Calling Procedure Passed in to Procedure To Act. Record of Caller Referenced Non-Local Data Needed to Restart Caller Local Variables for Scope Compiler Generated Returned Value Actual Parameters Optional Control Link Temporaries Saved Machine Status Local Data Optional Access Link

23 An Activation Record in C
Actual Parameters Supplied by Caller Needed to Restart Caller Local Variables for Scope If Callee Calls Another Procedure/Function Etc. Incoming Param 2 Incoming Param 1 Saved State Info Local Variables Temporary Storage Outgoing Parameters

24 Activation Records Procedure Activation Represents the Actions that Must Occur when a Caller Invokes a Callee: Transfer of Actuals into Formals by the Language’s Parameter Passing Mechanism Modification of Environment and State by Alloc of Memory for Variables that are Local to Callee Identification of the Control Return Point of Caller After Callee Complets Every Procedure Activation has Lifetime which is the Sequence of Steps (Code) of Procedure Body of Callee

25 What are Possible Activations?
Nested A calls B calls C Non-Overlapping A calls B B calls C Recursive A calls itself Concurrent A calls B (spawns process) A calls C (spawns process) B, C: execute in parallel and compete for Resources

26 Activation Tree Graphical Representation of Activations over Time

27 How is Tree Interpreted?
Each Node is a Specific Procedure Call Root Node is Start of Program Parent Node Flow from Parent to Child Caller to Callee Sibling Node All Nodes to Left have Completed Parent Comples when All Children Complete Utilize Control Stack to Represent Current State of an Activation s, q(1,9), q(1,3), q(2,3) Where is this on Prior Slide? Represents “state” at Point in Time

28 Activation Tree Where is: s, q(1,9), q(1,3), q(2,3)

29 Relationship to Environment and State
Recall: Assignments Change State Declarations Change Environment Differentiation also Possible from Static and Dynamic Levels Procedure Definition vs. Procedure Activation Name Declaration vs. Name Binding Scope of Declaration vs. Lifetime of Binding Environment State Compile Time Run Time Name Storage Value State Environment

30 Issues Impacting Runtime Environment
Are Procedure/Functions Recursive? What happens to Values of Local names after the Procedure Activation Completes? Can a Procedure Refer to Non-Local Names? What are Parameter Passing Mechanisms? How are Results Returned from Functions? Can Proc/Func be Returned as a Result? Passed as Parameters? Can Programmer Dynamically Allocate Storage? How is Deallocation Handled? These are: Rules of the Game What Every Software Engineer Should Know!

31 Activation Records Focus on Execution Environment for Imperative Language (C, C++, Java, Pascal, etc.) Code Reference by Program Counter Stack Contains Activation Records (Grows Down) Snapshot of Activations Status of Execution Heap for Dynamic Memory (Grows Up) Code Static Data Stack Heap

32 What Activation Record Contains?

33 Local Variables for Scope
Activation Record in C Actual Parameters Supplied by Caller Needed to Restart Caller Local Variables for Scope If Callee Calls Another Procedure/Function Etc. Incoming Param 2 Incoming Param 1 Saved State Info Local Variables Temporary Storage Outgoing Parameters When Callee Invokes/Activates Another Procedure, Outgoing Parameters of One Record are Incoming Parameters of Another Activation Record

34 Semantic Models of Parameter Passing
In mode Out mode Inout mode Copyright © 2015 Pearson. All rights reserved.

35 Models of Parameter Passing
Copyright © 2015 Pearson. All rights reserved.

36 Conceptual Models of Transfer
Physically move a value Move an access path to a value Copyright © 2015 Pearson. All rights reserved.

37 Pass-by-Value (In Mode)
The value of the actual parameter is used to initialize the corresponding formal parameter Normally implemented by copying Can be implemented by transmitting an access path but not recommended (enforcing write protection is not easy) Disadvantages (if by physical move): additional storage is required (stored twice) and the actual move can be costly (for large parameters) Disadvantages (if by access path method): must write-protect in the called subprogram and accesses cost more (indirect addressing) Copyright © 2015 Pearson. All rights reserved.

38 Pass-by-Result (Out Mode)
When a parameter is passed by result, no value is transmitted to the subprogram; the corresponding formal parameter acts as a local variable; its value is transmitted to caller’s actual parameter when control is returned to the caller, by physical move Require extra storage location and copy operation Potential problems: sub(p1, p1); whichever formal parameter is copied back will represent the current value of p1 sub(list[sub], sub); Compute address of list[sub] at the beginning of the subprogram or end? Copyright © 2015 Pearson. All rights reserved.

39 Pass-by-Value-Result (inout Mode)
A combination of pass-by-value and pass-by-result Sometimes called pass-by-copy Formal parameters have local storage Disadvantages: Those of pass-by-result Those of pass-by-value Copyright © 2015 Pearson. All rights reserved.

40 Pass-by-Reference (Inout Mode)
Pass an access path Also called pass-by-sharing Advantage: Passing process is efficient (no copying and no duplicated storage) Disadvantages Slower accesses (compared to pass-by-value) to formal parameters Potentials for unwanted side effects (collisions) Unwanted aliases (access broadened) fun(total, total); fun(list[i], list[j]; fun(list[i], i); All three could refer to the same memory locations Copyright © 2015 Pearson. All rights reserved.

41 Pass-by-Name (Inout Mode)
By textual substitution Formals are bound to an access method at the time of the call, but actual binding to a value or address takes place at the time of a reference or assignment Allows flexibility in late binding Implementation requires that the referencing environment of the caller is passed with the parameter, so the actual parameter address can be calculated Copyright © 2015 Pearson. All rights reserved.

42 Call By Value Environment and State of Actual/Formals is Different
Push on the stack a copy of the argument Size depends on argument type Any write operation overwrites the copy Copy automatically discarded on exit swap (x, y: integer); var temp: integer; begin temp := x; x := y; y := temp; end; . . . int a, b; swap (a, b) Print(a, b) x y x and y are in callee’s activation record (scope) a and b are in caller’s a b Do a and b Change?

43 Call By Reference Actuals and Formals Refer to Same Storage Location
Place the address of the actual on the stack A write operation simply follows the pointer Locations are Passed! Advantages? swap (var x, y: integer); var temp: integer; begin temp := x; x := y; y := temp; end; . . . int a, b; swap (a, b) Print(a, b) a and b are in caller’s activation record (scope) x y a b

44 C is Call by Value ONLY! Swap Will NOT Change a and b
Values are Unchanged! Fake “Call by Reference” main() { int x=5, y=10; swap (&x, &y); } void swap (int *px, *py); int temp; temp := *px; *px := *py; *py := temp; What is Effect of Call? main() { int x=5, y=10; swap (x, y); } void swap (int x, y); int temp; temp := x; x := y; y := temp;

45 C is Call by Value ONLY! main() { int x=5, y=10; swap (x, y); }
void swap (int x, y); int temp; temp := x; x := y; y := temp; main() { int x=5, y=10; swap (&x, &y); } void swap (int *px, *py); int temp; temp := *px; *px := *py; *py := temp;

46 Copy Restore Call by Value Result in Ada Programming Language
Three Types of Parameters in Ada: In: Corresponding to Value Parameters Out: Corresponding to Copy-Out Phase (Final r-value of Formals Copied out to Actuals) Inout: Either Call by Reference True Call by Value Result (Compiler Dependent) How Does this work?

47 Copy Restore Key Interpretation
If an Actual has Just an r-value - Call By Value If an Actual has a l-value then Copy Out Formal to Actual – Storage not Shared! What Does Following Code do: program copyout (input, output); var a: integer; procedure unsafe (var x: integer); begin x := 2; a := 0; end; a := 1; unsafe(a); writeln(a); end. x a

48 Copy Restore – Approach 1
Actual has Just an r-value - Call By Value What Does Following Code do: program copyout (input, output); var a: integer; procedure unsafe (var x: integer); begin x := 2; a := 0; end; a := 1; unsafe(a); writeln(a); end. x a

49 Copy Restore – Approach 2
What Does Following Code do: program copyout (input, output); var a: integer; procedure unsafe (var x: integer); begin x := 2; a := 0; end; a := 1; unsafe(a); writeln(a); end. x a

50 Call By Name Two Views of this Process
Macro Expansion in C where a Substitution of Procedure Code (the Callee) Occurs to Replace a Call (in Caller) Substitution of the Actual Parameters (from Caller) into the Procedure Itself (into Callee) Suppoted in C using #define substitution What are Implications of each Approach?

51 Version 1: Macro Expansion
int x = MAXBUF + 1; int m = 0; void p(void) {m=(m+1)%x;} int out (void) { int x; x = buf[m]; { m = (m+1) % x; } return x; } int x = MAXBUF + 1; int m = 0; void p(void) {m=(m+1)%x;} int out (void) { int x; x = buf[m]; p(); return x; } What Happens when { m = (m+1) % x; } is substituted for p()? How Does Resulting Code Work?

52 Version 2: Actual Substitution
Procedure Definition void q(int y) { int i; i = 5; y = y + 1; } Procedure Call main() { int i; int A[10]; i = 6; q (A[i]); } What is a result of this Call by Substitution A[i] (actual) into y (formal)? { int i; i = 5; A[i] = A[i] + 1; }

53 Problems with Macro Expansion
#define swap(a,b) temp=a; a=b; b=temp; if (x<y) swap(x,y); Textually expands to if (x<y) temp=x; x=y; y=temp; Why not #define swap(a,b) { int temp=a; a=b; b=temp; }? Instead #define swap(a,b) do { int temp=a; a=b; b=temp; } while(false); Fixes type of swapped variables

54 Parameter Passing in PL
Fortran Always use inout-mode model of parameter passing Before Fortran 77, mostly used pass-by-reference Later implementations mostly use pass-by-value-result C mostly pass by value Pass-by-reference is achieved using pointers as parameters int *p = { 1, 2, 3 }; void change( int *q) { q[0] = 4; } main() { change(p); /* p[0] = 4 after calling the change function */

55 Parameter Passing in PL
C Pass-by reference: value of pointer is copied to the called function and nothing is copied back #include <stdio.h> void swap (int *p, int *q) { int *temp; temp = p; p = q; q = temp; } main() { int p[] = {1, 2, 3}; int q[] = {4, 5, 6}; int i; swap (p, q); When return, p and q will be pointing to the same thing as before the swap call.

56 Parameter Passing in PL
C++ includes a special pointer type called a reference type void GetData(double &Num1, const int &Num2) { int temp; for (int i=0; i<Num2; i++) { cout << “Enter a number: “; cin >> temp; if (temp > Num1) { Num1 = temp; return; } } Num1 and Num2 are passed by reference const modifier prevents a function from changing the values of reference parameters Referenced parameters are implicitly dereferenced Why do we need a constant reference parameter? Dereferencing: resolves the pointer (gets at the l-value of the pointer variable) Num1 and Num2 pointers: *Num1 refers to the data value of the address pointed to by Num1 Why need constant reference params? When you pass a const reference it is assumed that the inner statements do not modify the passed object.

57 Parameter Passing in PL
Ada Reserved words: in, out, in out (in is the default mode) procedure temp(A : in out Integer; B : in Integer; C : in Integer ) out mode can be assigned but not referenced in mode can be referenced but not assigned in out can be both referenced and assigned Fortran Semantic modes are declared using Intent attribute Subroutine temp(A, B, C) Integer, Intent(Inout) :: A Integer, Intent(In) :: B Integer, Intent(Out) :: C

58 Programming Language Principles
Subroutines (Part 2) Programming Language Principles Lecture 25 Prepared by Manuel E. Bermúdez, Ph.D. Associate Professor University of Florida

59 Parameter Passing Formal parameters: Parameters that appear in the declaration of a subroutine Actual parameters: expressions actually used in procedure call. Some languages allow only ONE parameter passing mode: C, Fortran, ML, Lisp. Other languages allow multiple parameter passing modes: Pascal, Modula, Ada, Java

60 Main Parameter Passing Modes
1) Call by value: Pass the value of the argument. C, C++, Pascal (also allows pass by reference), Java (primitive types). Can be expensive: large structures are copied. 2) Call by reference: Pass the address of the argument. Smalltalk, Lisp, ML, Clu, C++, Java (non primitive types, including arrays). C, C++ have const mode: cannot change parameter. 3) Call by name: Pass the text of the argument. C pre-processor (#define) More later.

61 Choosing Parameter Passing Mode
Many languages provide a choice: Pass by value: Intent is to not modify the argument. Pass by reference: Intent is to modify the argument. Often used to avoid expense of copying large structure, even if there’s no intent to modify it. Leaves door open for mistakes. In some languages (C, C++) modifying the argument can be explicitly forbidden (const)

62 Parameter Passing in Ada
ADA provides 3 modes: in, out, in-out. In: From caller to callee (call by value). Out: From callee to caller (call by result). In-out: Uses both. (call by value/result). Ada specifies that all three are to be implemented by copying the values. However, Ada specifically permits passing either values or addresses.

63 Parameter Passing Modes: Example
var y:integer; procedure A(x:integer); begin write(x); x := 1; write(y+x); end; y := 5; A(y); write(y); Pass by value: Output is (5,6,5) x y

64 Parameter Passing Modes: Example
var y:integer; procedure A(x:integer); begin write(x); x := 1; write(y+x); end; y := 5; A(y); write(y); Pass by reference: Output is (5,2,1) x y

65 Parameter Passing Modes: Example
var y:integer; procedure A(x:integer); begin write(x); x := 1; write(y+x); end; y := 5; A(y); write(y); Pass by result: Output is (??,6,1) x y

66 Parameter Passing Modes: Example
var y:integer; procedure A(x:integer); begin write(x); x := 1; write(y+x); end; y := 5; A(y); write(y); Pass by value/result: Output is (5,6,1) x y

67 Parameter Passing Modes: Example
var y:integer; procedure A(x:integer); begin write(x); x := 1; write(y+x) ; end; y := 5; A(y); write(y); Pass by name: Output is (5,2,1) (same as pass by reference) x y

68 Call by Name (cont’d) Pass by name literally substitutes n for a, and m for b. Result: t := n; n := m; m := t; swap is achieved. procedure swap(a,b:integer); var t:integer: begin t := a: a := b: b := t; end; ... var n,m:integer; n := 3; m := 4; swap(n,m);

69 Call by Name (cont’d) procedure swap(a,b:integer); var t:integer: begin t := a: a := b: b := t; end; ... var i:integer; var A: array[1..10] of integer; i := 3; A[3] := 17; swap(i,A[i]); However, attempting to swap i and A[i] results in t := i; i := A[i]; A[i] := t; 17 assigned to i, but 3 assigned to A[17] (out of range) swap not achieved.

70 Parameter Passing in Pascal
var y:integer; procedure A(var x:integer); begin write(x); x := 1; write(y+x); end; y := 5; A(y); write(y); Use keyword var to effect pass by reference. With var , output is (5,2,1). Without var, output is (5,6,5)

71 Variable number of arguments
In C, C++: #include <stdarg.h> /* macros and types defns */ int printf (char *format, ...) { va_list args; va_start (args, format); char cp = va_arg(args,char); double dp = va-arg(args,double); } Here we assume two arguments, of type char and double, are expected. If not, chaos will ensue ... part of code

72 Function Return Values
Many languages restrict return types from functions. Algol 60, Fortran: must be a scalar value. Pascal, Modula-2: must be scalar or pointer. Modula-3, Ada 95: allow a function to return a subroutine C: function can return a pointer to a function. Lisp, ML, Algol 68, RPAL: returning closures is common.

73 Implementing Parameter Passing
Code Data Heap Stack Memory contents program code global and static data Dynamically allocated variables Most subprograms: static or stack-dynamic: Stack-dynamic: allocate space for local vars and referencing environment when Execute the subprogram. The referencing env goes away when the subprogram Terminates. local data

74 Implementing Parameter Passing
Pass by Value Values copied into stack locations Stack locations serve as storage for corresponding formal parameters Pass by Result Implemented opposite of pass-by-value Values assigned to actual parameters are placed in the stack, where they can be retrieved by calling program unit upon termination of called subprogram Pass by Value Result Stack location for parameters is initialized by by the call and then copied back to actual parameters upon termination of called subprogram

75 Implementing Parameter Passing
Pass by Reference Regardless of type of parameter, put the address in the stack For literals, address of literal is put in the stack For expressions, compiler must build code to evaluate expression before the transfer of control to the called subprogram Address of memory cell in which code places the result of its evaluation is then put in the stack Compiler must make sure to prevent called subprogram from changing parameters that are literals or expressions Access to formal parameters is by indirect addressing from the stack location of the address

76 Implementing Parameter Passing
val res val-res ref sub(w,x,y,z) sub(a,b,c,d) Main program calls sub(w,x,y,z) where w is passed by value, x is passed by result, y is passed by value-result, and z is passed by reference

77 Implementing Parameter Passing
Pass by Name run-time resident code segments or subprograms evaluate the address of the parameter called for each reference to the formal Very expensive, compared to pass by reference or value-result

78 Parameter Passing Methods of Major Languages
C Pass-by-value Pass-by-reference is achieved by using pointers as parameters C++ A special pointer type called reference type for pass-by-reference Java All parameters are passed are passed by value Object parameters are passed by reference Copyright © 2015 Pearson. All rights reserved.

79 Parameter Passing Methods of Major Languages (continued)
Fortran Parameters can be declared to be in, out, or inout mode C# - Default method: pass-by-value Pass-by-reference is specified by preceding both a formal parameter and its actual parameter with ref PHP: very similar to C#, except that either the actual or the formal parameter can specify ref Perl: all actual parameters are implicitly placed in a predefined array Python and Ruby use pass-by-assignment (all data values are objects); the actual is assigned to the formal Copyright © 2015 Pearson. All rights reserved.

80 Type Checking Parameters
Considered very important for reliability FORTRAN 77 and original C: none Pascal and Java: it is always required ANSI C and C++: choice is made by the user Prototypes Relatively new languages Perl, JavaScript, and PHP do not require type checking In Python and Ruby, variables do not have types (objects do), so parameter type checking is not possible Copyright © 2015 Pearson. All rights reserved.

81 Multidimensional Arrays as Parameters
If a multidimensional array is passed to a subprogram and the subprogram is separately compiled, the compiler needs to know the declared size of that array to build the storage mapping function Copyright © 2015 Pearson. All rights reserved.

82 Multidimensional Arrays as Parameters
C: Uses row major order for matrices address(mat[i, j]) = address(mat[0,0]) + i*num_columns + j Must specify num_columns but not num_rows void fun (int matrix[][10]) { … } void main() { int mat[5][10]; fun(mat); } Does not allow programmers to write function that accepts different number of columns Alternative: use pointers C: row-major order (collections/columns of rows of arrays) Fortran: column major order (rows of columns of arrays)

83 Multidimensional Arrays as Parameters
Ada: type Mat_Type is array (Integer range <> Integer range<>) of Float; Mat1 : Mat_Type(1..100, 1..20); function Sumer(Mat : in Mat_Type) return Flat is Sum : Float := 0.0; begin for Row in Mat’range(1) loop for Col in Mat’range(2) loop Sum := Sum + Mat(Row, Col); end loop; return Sum; end Sumer; No need to specify size of array Use range attribute to obtain size of arrray

84 Multidimensional Arrays as Parameters
Fortran Array parameters must have declaration after the header Subroutine Sub (Matrix, Rows, Cols, Result) Integer, Intent(In) :: Rows, Cols Real, Dimension(Rows, Cols), Intent(In) :: Matrix Real, Intent (In) :: Result End Subroutine Sub

85 Subprogram Names as Parameters
Issues: Are parameter types checked? Early Pascal and FORTRAN 77 do not; later versions of Pascal and FORTRAN 90 do Ada does not allow subprogram parameters Java does not allow method names to be passed as parameters C and C++ - pass pointers to functions; parameters can be type checked What is the correct referencing environment for a subprogram that was sent as a parameter? Environment of the call statement that enacts the passed subprogram Shallow binding Environment of the definition of the passed subprogram Deep binding Environment of the call statement that passed the subprogram as actual parameter Ad hoc binding (Has never been used) SHALLOW BINDING - the nonlocal referencing environment of a procedure instance is the referencing environment in force at the time it (the procedure) is invoked. Original LISP works this way by default. DEEP BINDING - the nonlocal referencing environment of a procedure instance is the referencing environment in force at the time the procedure's declaration is elaborated. For procedures passed as parameters, this environment is the same as would be extant if the procedure were actually called at the point where it was passed as an argument. When the procedure is passed as an argument, this referencing environment is passed as well. When the procedure is eventually invoked (by calling it using the corresponding formal parameter), this saved referencing environment is restored. LISP funarg and procedures in Algol and Pascal work this way.

86 Parameters that are Subprogram Names: Referencing Environment
Shallow binding: The environment of the call statement that enacts the passed subprogram - Most natural for dynamic-scoped languages Deep binding: The environment of the definition of the passed subprogram - Most natural for static-scoped languages Ad hoc binding: The environment of the call statement that passed the subprogram Copyright © 2015 Pearson. All rights reserved.

87 Subprogram Names as Parameters
function sub1() { var x; function sub2() { alert(x); }; function sub3() { x = 3; sub4(sub2); } function sub4(subx) { x = 4; sub2(); x = 1; sub3(); Shallow binding: Referencing environment of sub2 is that of sub4 Deep binding Referencing environment of sub2 is that of sub1 Ad-hoc binding Referencing environment of sub2 is that of sub3 Main: invoke sub3 sub3: sub4 (sub2) % Deep binding: ref env of sub2 is sub1 (based on decl) sub4: (subx) sub2 % Ad-hoc binding: ref env of sub2 is sub3 sub2: alert(x) % Shallow binding: where it was called from, ref env is sub4

88 Overloaded Subprograms
An overloaded subprogram is one that has the same name as another subprogram in the same referencing environment Every version of an overloaded subprogram has a unique protocol C++, Java, C#, and Ada include predefined overloaded subprograms In Ada, the return type of an overloaded function can be used to disambiguate calls (thus two overloaded functions can have the same parameters) Ada, Java, C++, and C# allow users to write multiple versions of subprograms with the same name Copyright © 2015 Pearson. All rights reserved.

89 Generic Subprograms A generic or polymorphic subprogram takes parameters of different types on different activations Overloaded subprograms provide ad hoc polymorphism Subtype polymorphism means that a variable of type T can access any object of type T or any type derived from T (OOP languages) A subprogram that takes a generic parameter that is used in a type expression that describes the type of the parameters of the subprogram provides parametric polymorphism - A cheap compile-time substitute for dynamic binding Copyright © 2015 Pearson. All rights reserved.

90 Generic Subprograms (continued)
Versions of a generic subprogram are created implicitly when the subprogram is named in a call or when its address is taken with the & operator Generic subprograms are preceded by a template clause that lists the generic variables, which can be type names or class names template <class Type> Type max(Type first, Type second) { return first > second ? first : second; } Copyright © 2015 Pearson. All rights reserved.

91 Generic Subprograms (continued)
Java Differences between generics in Java 5.0 and those of C++: 1. Generic parameters in Java 5.0 must be classes 2. Java 5.0 generic methods are instantiated just once as truly generic methods 3. Restrictions can be specified on the range of classes that can be passed to the generic method as generic parameters 4. Wildcard types of generic parameters Copyright © 2015 Pearson. All rights reserved.

92 Generic Subprograms (continued)
Java 5.0 (continued) public static <T> T doIt(T[] list) { … } - The parameter is an array of generic elements (T is the name of the type) - A call: doIt<String>(myList); Generic parameters can have bounds: public static <T extends Comparable> T doIt(T[] list) { … } The generic type must be of a class that implements the Comparable interface Copyright © 2015 Pearson. All rights reserved.

93 Generic Subprograms (continued)
Java 5.0 (continued) Wildcard types Collection<?> is a wildcard type for collection classes void printCollection(Collection<?> c) { for (Object e: c) { System.out.println(e); } - Works for any collection class Copyright © 2015 Pearson. All rights reserved.

94 Generic Subprograms (continued)
C# Supports generic methods that are similar to those of Java One difference: actual type parameters in a call can be omitted if the compiler can infer the unspecified type Another – C# 2005 does not support wildcards Copyright © 2015 Pearson. All rights reserved.

95 Generic Subprograms (continued)
F# Infers a generic type if it cannot determine the type of a parameter or the return type of a function – automatic generalization Such types are denoted with an apostrophe and a single letter, e.g., ′a Functions can be defined to have generic parameters let printPair (x: ′a) (y: ′a) = printfn ″%A %A″ x y - %A is a format code for any type - These parameters are not type constrained Copyright © 2015 Pearson. All rights reserved.

96 Generic Subprograms (continued)
F# (continued) If the parameters of a function are used with arithmetic operators, they are type constrained, even if the parameters are specified to be generic Because of type inferencing and the lack of type coercions, F# generic functions are far less useful than those of C++, Java 5.0+, and C# 2005+ Copyright © 2015 Pearson. All rights reserved.

97 Generic queue package in Ada:
Queue contains up to max_items objects of type item. Operations are enqueue and dequeue. Implemented as circular list. Generics must be instantiated.

98 Generic queues in C++: Generic classes must be instantiated. Generic functions need not be instantiated.

99 Generics in Ada (cont’d)
Ada doesn’t allow subroutines as parameters. Can use generics instead:

100 Generics in Ada (cont’d)
Now, we can instantiate: subtype index is integer range ; scores: array(index) of integer; function foo (n: in integer) return integer is begin end; procedure apply_to_ints is new apply_to_array (integer, int_array, foo); apply_to_ints(scores);

101 User-Defined Overloaded Operators
Operators can be overloaded in Ada, C++, Python, and Ruby A Python example def __add__ (self, second) : return Complex(self.real + second.real, self.imag + second.imag) Use: To compute x + y, x.__add__(y) Copyright © 2015 Pearson. All rights reserved.

102 Coroutines A coroutine is a subprogram that has multiple entries and controls them itself – supported directly in Lua Also called symmetric control: caller and called coroutines are on a more equal basis A coroutine call is named a resume The first resume of a coroutine is to its beginning, but subsequent calls enter at the point just after the last executed statement in the coroutine Coroutines repeatedly resume each other, possibly forever Coroutines provide quasi-concurrent execution of program units (the coroutines); their execution is interleaved, but not overlapped Copyright © 2015 Pearson. All rights reserved.

103 Coroutines Illustrated: Possible Execution Controls
Copyright © 2015 Pearson. All rights reserved.

104 Coroutines Illustrated: Possible Execution Controls
Copyright © 2015 Pearson. All rights reserved.

105 Coroutines Illustrated: Possible Execution Controls with Loops
Copyright © 2015 Pearson. All rights reserved.

106 Summary A subprogram definition describes the actions represented by the subprogram Subprograms can be either functions or procedures Local variables in subprograms can be stack-dynamic or static Three models of parameter passing: in mode, out mode, and inout mode Some languages allow operator overloading Subprograms can be generic A coroutine is a special subprogram with multiple entries Copyright © 2015 Pearson. All rights reserved.


Download ppt "Chapter 9 Subprograms."

Similar presentations


Ads by Google