Basic Definitions• A subprogram definition describes the interface and the actions of the subprogram • A subprogram headerp g is the first part of the p definition, including the name, t
Trang 1• Design Issues for Subprograms
Local Referencing Environments
• Local Referencing Environments
• Parameter-Passing Methods
• Parameters That Are Subprogram Names
• Overloaded Subprograms
• Generic Subprograms Generic Subprograms
• Design Issues for Functions
• User-Defined Overloaded Operators
• Coroutines
Trang 2• Each subprogram has a single entry point
• The calling (sub)program (caller) is suspended during execution of the called subprogram
during execution of the called subprogram
(callee)
• Control always returns to the caller when the callee’s execution terminates
Trang 3Basic Definitions
• A subprogram definition describes the interface
and the actions of the subprogram
• A subprogram headerp g is the first part of the p
definition, including the name, the kind of
subprogram, and the formal parameters
subprogram, and the formal parameters
• The parameter profile (signature) of a subprogram
is the number, order, and types of its parameters
• The protocol is a subprogram’s parameter profile Copyright © 2006 Addison-Wesley All rights reserved 1-5and its return type, if it is a function
Basic Definitions (cont.)
• A subprogram declaration provides the protocol, but not the body of the subprogram
– Function declarations in C/C++ are often called
prototypes
– Subprogram declarations in Ada/Pascal are
• A formal parameter is a dummy variable listed in the subprogram header and used in the
subprogram
• An actual parameter represents a R-value or
L-value used in the subprogram call statement
Trang 4– Through parameter passing
• Parameter passing is more flexible
– Parameter passing is a parameterized computation
– The only way the computation can proceed on different data is to assign new values to nonlocals between calls
data is to assign new values to nonlocals between calls
to the subprogram
– Nonlocals that are visible to the subprogram where
Copyright © 2006 Addison-Wesley All rights reserved 1-7
Nonlocals that are visible to the subprogram where access to them is desired or not poor reliability
Actual/Formal Parameter
• Positional parameters
– The binding of actual parameters to formal
parameters is by position: the first actual
parameter is bound to the first formal parameter
parameter is bound to the first formal parameter and so forth
– A good method for relatively short parameter lists A good method for relatively short parameter lists
• Keyword parameters
– The name of the formal parameter to which an The name of the formal parameter to which an
actual parameter is to be bound is specified with the actual parameter
– Parameters can appear in any order
Trang 5Actual/Formal Parameter (cont.)
• Example: Ada and FORTRAN 90 allow to mix
positional and keyword parameters in a call
SUMER(MY_LENGTH, LIST => MY_ARRAY, SUM => MY_SUM);
Copyright © 2006 Addison-Wesley All rights reserved 1-9
Formal Parameter Default Values
• In certain languages (e.g., C++, Ada), formal parameters can have default values
• In C++, default parameters must appear last because parameters are positionally associated
• Example: Ada
f ti COMP(A FLOAT B INTEGER 1 C FLOAT) function COMP(A:FLOAT; B:INTEGER := 1; C:FLOAT) return FLOAT;
PAY := COMP(20.0, C => 0.75) : CO ( 0.0, C 0 5)
• Example: C++
float comp(float A, float C, int B = 1); p( , , )
pay = comp(20, 0.75);
Trang 6Procedures and Functions
• There are two categories of subprograms
– Procedures are collection of statements that define parameterized computations
Procedures provide user-defined statements
– Functions Functions structurally resemble procedures but are structurally resemble procedures but are semantically modeled on mathematical functions
Functions provide user defined operators
Functions provide user-defined operators
They are expected to produce no side effects
I ti f ti h id ff t
Copyright © 2006 Addison-Wesley All rights reserved 1-11
In practice, functions may have side effects
Design Issues for Subprograms
• What parameter passing methods are provided?
• Are parameter types checked?
• Are local variables static or dynamic?
• Can subprogram definitions appear in other
subprogram definitions?
• What is the referencing environment of a passed subprogram?
• Can subprograms be overloaded?
• Can subprogram be generic?
• Can subprogram be compiled independently?
Trang 7Local Referencing Environments
• Local variables can be stack-dynamic
– Advantages Advantages
Support for recursion
Storage for locals is shared among subprograms
– Disadvantages
Allocation/deallocation, initialization time
Indirect addressing
Subprograms cannot be history sensitive
• Local variables can be static
– More efficient (direct addressing)
– No run-time overhead
– Cannot support recursion
Copyright © 2006 Addison-Wesley All rights reserved 1-13
Cannot support recursion
– History sensitive
Local Referencing Environments (cont.)
• Language Examples:
implementor can choose either (user can force
static with SAVE)
C/C++: both (variables declared to be static, C/C++: both (variables declared to be static,
default they are stack-dynamic)
ALGOL 60 Pascal Java and Ada: stack dynamic
only
Trang 8Parameter Passing Methods
– inout mode : Formal parameters can do both
• Conceptual models of transfer
– Physically move a value
Copyright © 2006 Addison-Wesley All rights reserved 1-15
– Move an access path
Models of Parameter Passing (cont.)
Trang 9Parameter Passing Methods (cont.)
• Ways in which parameters are transmitted to and/or from callee
– Pass-by-value Pass by value
Copyright © 2006 Addison-Wesley All rights reserved 1-17
Pass-by-Value (in-mode Model)
• The value of the actual parameter is used to
initialize the corresponding formal parameter
Additional storage is required
Storage and copy operations can be costly
Storage and copy operations can be costly
– Can be implemented by transmitting an access path but not recommended
Must write-protect in the called subprogram
A (i di dd i )
Accesses cost more (indirect addressing)
Trang 10Pass-by-Result (out-mode Model)
• When a parameter is passed by result
– No value is transmitted to the callee
– The corresponding formal parameter acts as a The corresponding formal parameter acts as a local variable; its value is transmitted to caller’s actual parameter when control is returned to the
actual parameter when control is returned to the caller
Require extra storage location and copy
– Require extra storage location and copy
operation
Copyright © 2006 Addison-Wesley All rights reserved 1-19
Potential Problems
• There can be an actual parameter collision
procedure sub(y: int, z: int); … sub(x, x); …
Value of x depends on order of assignments at the return
• The implementor may be able to choose between two different times to evaluate the addresses of the actual parameters: at the time of the call or at the time of the return
– Suppose that list[idx] is an actual parameter If idx
is changed by the callee, then the address of g
list[idx] will change between the call and the return
Trang 11Pass-by-Value-Result (in-out Mode)
• A combination of pass-by-value and
pass-by-result
• Sometimes calledSometimes called pass-by-copypass by copy
• Formal parameters have local storage
• Disadvantages:
– Those of pass-by-result
– Those of pass-by-value
Copyright © 2006 Addison-Wesley All rights reserved 1-21
Pass-by-Reference (in-out Mode)
• Pass an access path to the callee
• Also called pass-by-sharing
• Passing process is efficient (no copying and noPassing process is efficient (no copying and no duplicated storage)
– Potentials for unwanted side effects
– Unwanted aliases (access broadened)
Trang 12Problems of Aliases
• Сollisions between actual parameters
void fun(int * first, int * second);
void fun(int first, int second); …
fun(&total, &total);
fun(&list[i], &list[j]); // i = j
• Сollisions between formal parameters and
nonlocal variables that are visible
int * global; … g
void sub(int * local) {
extern int * global; …
• Formal parameters are bound to an access
method at the time of the call, but actual
method at the time of the call, but actual
binding to a value takes place at the time of a reference or assignment
• Allows flexibility in late binding
Trang 13Pass-by-Name (cont.)
• The form of the actual parameter dictates the
implementation model of pass-by-name
parameters If actual parameter is
– A scalar variable, by-name is equivalent to by-reference
– A constant expression, pass-by-name is equivalent to pass-by-value
An array element pass by name is like nothing else
– An array element, pass-by-name is like nothing else (example 1)
– An expression with a reference to a variable
pass-by-Copyright © 2006 Addison-Wesley All rights reserved 1-25
An expression with a reference to a variable, pass by name is also like nothing else (example 2)
Trang 14Pass-by-Name: Example 2
// Assume k is a nonlocal variable
1 procedure sub1(x: int; y: int; z: int);
Copyright © 2006 Addison-Wesley All rights reserved 1-27
Pass-by-Name: Jensen’s Device
real procedure SUM(ADDER, INDEX, LENGTH);
f INDEX 1 t 1 til LENGTH d
for INDEX := 1 step 1 until LENGTH do
TEMPSUM := TEMPSUM + ADDER;
SUM := TEMPSUM; ;
end;
If A is a scalar, then SUM(A, I, 100) produces , ( , , ) p
the result 100 * A
Trang 15Pass-by-Name: Jensen’s Device
real procedure SUM(ADDER, INDEX, LENGTH);
f INDEX 1 t 1 til LENGTH d
for INDEX := 1 step 1 until LENGTH do
TEMPSUM := TEMPSUM + ADDER;
SUM := TEMPSUM; ;
end;
If A is an array of 100 reals, then
f Copyright © 2006 Addison-Wesley All rights reserved 1-29
SUM(A[I], I, 100) returns the sum of the
elements of A
Pass-by-Name: Jensen’s Device
real procedure SUM(ADDER, INDEX, LENGTH);
for INDEX := 1 step 1 until LENGTH do
TEMPSUM := TEMPSUM + ADDER;
SUM := TEMPSUM;
end;
If A is an array of 100 reals, then
SUM(A[I]*A[I] I 100) returns the sum of
SUM(A[I]*A[I], I, 100) returns the sum of
the squares of the elements of A
Trang 16Pass-by-Name: Jensen’s Device
real procedure SUM(ADDER, INDEX, LENGTH);
for INDEX := 1 step 1 until LENGTH do
TEMPSUM := TEMPSUM + ADDER;
SUM := TEMPSUM;
end;
If A and B are arrays of 100 reals, then
SUM(A[I]*B[I] I 100) returns the inner
Copyright © 2006 Addison-Wesley All rights reserved 1-31
SUM(A[I]*B[I], I, 100) returns the inner
terms of execution efficiency
– It’s difficult to implement and can confuse both readers and writers of programs that use them readers and writers of programs that use them
Trang 17Pass-by-name Copyright © 2006 Addison-Wesley All rights reserved 1-33
( [ ] , [ ]);
writeln(‘a[2] = ’, a[2]);
end.
a[1] = 2 a[2] = 2
Parameter Passing Methods of Major
Languages
• Ada: All three semantic modes are available
The actual parameter’s value cannot be changed
The formal parameter is a constant and allows only
The formal parameter is a constant and allows only reading
– in out
The actual parameter’s value may be redefined
The formal parameter can be read and written
t
– out
The actual parameter's value before the call is
irrelevant, it will get a value in the call g
The formal parameter can be read and written
Trang 18Parameter Passing Methods of Major
– The corresponding formal parameters can be pointers
to constants, which provide the efficiency of reference with in-mode semantics
pass-by-• Java
Copyright © 2006 Addison-Wesley All rights reserved 1-35
– All scalar parameters are passed by value
– Object parameters are passed by reference
Parameter Passing Methods of Major
Languages (cont )
• C#
D f l h d b l
– Default method: pass-by-value
– Pass-by-reference is specified by preceding both a
formal parameter and its actual parameter with refp p
• Fortran
– Always used the inout semantics model
– Before Fortran 77: pass-by-reference
– Fortran 77 and later: scalar variables are often
passed by value result
• Pascal and Modula-2
– Default is pass-by-value Default is pass by value
– Pass-by-reference is optional
Trang 19Type-Checking Parameters
• Software reliability demands that the actual
parameters be checked for consistency with the types of the corresponding formal parameters
• FORTRAN 77 and original C: none
• Pascal, FORTRAN 90, Java, and Ada: it is alwaysPascal, FORTRAN 90, Java, and Ada: it is always required
In C++ all functions must have their formal
• In C++, all functions must have their formal
parameters in prototype form, so type-checking
Copyright © 2006 Addison-Wesley All rights reserved 1-37parameters are required
Type-Checking Parameters (cont.)
• In ANSI C, the formal parameters of functions can be defined in two ways
– The way of the original C: Using this method
avoids type checking
Trang 20Implementing Parameter Passing
• In most language parameter communication
takes place through the run time stack
• Pass-by-value: copy value to the stack;
references are indirect to the stack
• Pass-by-result is implemented as the opposite of pass-by-value
• Pass-by-value-result can be implemented as a combination of pass-by-value and pass-by-
communication to the callee is required,
inadvertent and erroneous changes may be
made to the actual parameter
Trang 21i = b;
vs Pass by reference i = b;
} void main() {
Trang 22Stack Implementation of Parameter-Passing
Copyright © 2006 Addison-Wesley All rights reserved 1-43
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 p p
declared size of that array to build the storage mapping function
Trang 23Multidimensional Arrays as Parameters: C/C++
• Programmer is required to include the declared sizes of all but the first subscript in the actual
sizes of all but the first subscript in the actual parameter
Disallows writing flexible subprograms
– Disallows writing flexible subprograms
void fun(int matrix[][3])
• Pass a pointer to the array and the sizes of the
• Pass a pointer to the array and the sizes of the dimensions as other parameters; the user
should include the storage mapping function
#define a(r, c) (*(a + ((r) * num_cols) + (c))) void fun(int *a, int num_rows, int num_cols) {
Copyright © 2006 Addison-Wesley All rights reserved 1-45
type TblType = array[1 5, 1 10] of integer;
– A type name not description must be used in
– A type name, not description, must be used in all formal parameter declarations
d P(T TblT )
procedure P(T : TblType);
Trang 24Multidimensional Arrays as Parameters: Ada
• Ada has constrained arrays (like Pascal) and
unconstrained array types
• An Ada unconstrained array type
type MATRIX_TYPE is array( INTEGER range <>,
INTEGER range <> ) of FLOAT; MATRIX_1 : MATRIX_TYPE (1 10, 1 20);
function SUMER(MAT: in MATRIX_TYPE) return FLOAT is begin
for ROW in MAT’range(1) loop
for COL in MAT’range(2) loop
… end loop;
Copyright © 2006 Addison-Wesley All rights reserved 1-47
– For multi-dimensional arrays, the subscripts
allow the compiler to build the storage-mapping
f nction
SUBPROGRAM SUB(MATRIX, ROWS, COLS, RESULT) INTEGER ROWS COLS
INTEGER ROWS, COLS
REAL MATRIX (ROWS, COLS), RESULT
…
END
Trang 25Multidimensional Arrays as Parameters: Java and C#
• Arrays are objects; they are all
single-dimensioned but the elements can be arrays
• Each array inherits a named constant (length in
J L th i C#) th t i t t th l th f
Java, Length in C#) that is set to the length of
the array when the array object is created
float sumer(float mat[][]) {
float sum = 0.0f;
for (int row = 0; row < mat.length; row++) {
for (int col = 0; row < mat[row].length; col++) { sum += mat[row][col];
• The above considerations are in conflict
– One-way (in) parameters are safe since they do not allow aliases but are expensive when large
not allow aliases, but are expensive when large data structures must be copied
– Pass-by-reference is fastest way to pass
– Pass-by-reference is fastest way to pass
structures of significant size and it allows aliasing – Functions should not allow reference parameters Functions should not allow reference parameters (functional side effects)