Upload
lini-ickappan
View
240
Download
0
Embed Size (px)
Citation preview
8/11/2019 subprogram(robert text).ppt
1/109
ISBN 0-321-19362-8
Chapter 9
Subprograms
8/11/2019 subprogram(robert text).ppt
2/109
Chapter 9 Topics
Introduction
Fundamentals of Subprograms
Design Issues for Subprograms
Local Referencing Environments
Parameter-Passing Methods
Other types of parameters
Overloaded Subprograms
Generic Subprograms
Design Issues for Functions
User-Defined Overloaded Operators
Coroutines
8/11/2019 subprogram(robert text).ppt
3/109
Introduction
Two fundamental abstraction facilities
Process abstraction (this chapter)
Data abstraction (Chapter 11)
8/11/2019 subprogram(robert text).ppt
4/109
Chapter 9 Topics
Introduction
Fundamentals of Subprograms
Design Issues for Subprograms
Local Referencing Environments
Parameter-Passing Methods
Parameters that are Subprogram Names
Overloaded Subprograms
Generic Subprograms
Design Issues for Functions
User-Defined Overloaded Operators
Coroutines
8/11/2019 subprogram(robert text).ppt
5/109
Fundamentals of Subprograms
General characteristics of subprograms:
1. A subprogram has a single entry point
2. The caller is suspended during execution of the
called subprogram3. Control always returns to the caller when the
called subprograms execution terminates
8/11/2019 subprogram(robert text).ppt
6/109
Fundamentals of Subprograms
Basic definitions:
A subprogram definitionis a description of the
actions of the subprogram abstraction
A subprogram callis an explicit request that thesubprogram be executed
A subprogram headeris the first line of the
definition, including the name, the kind of
subprogram, and the formal parameters Theparameter profile(signature) of a subprogram
is the number, order, and types of its parameters
8/11/2019 subprogram(robert text).ppt
7/109
Fundamentals of Subprograms
Basic definitions (continued):
Theprotocolof a subprogram is its parameter
profile plus, if it is a function, its return type
A subprogram declarationprovides the protocol,but not the body, of the subprogram (called
functionprototypesin C/C++)
Java and C# do not use subprogram declarations
A formal parameteris a dummy variable listed inthe subprogram header and used in the subprogram
An actual parameterrepresents a value or address
used in the subprogram call statement
8/11/2019 subprogram(robert text).ppt
8/109
Fundamentals of Subprograms
Access to data in subprogram Global variables (dangerous)
Parameters
Formal parameters. The parameters in thesubprogram header.
Actual parameters. The parameters used in
the subprogram call.
8/11/2019 subprogram(robert text).ppt
9/109
Fundamentals of Subprograms
Actual/Formal Parameter Correspondence:
1. Positional
2. Keyword. Actual and formal parameters bound
explicitly e.g. in Ada: SORT(LIST => A, LENGTH => N);
This binds the formal parameter LIST to the actual parameter
A and the formal LENGTH to the actual N.
Can mix positional and keyword param, but once use a
keyword, rest of actuals must use keyword.
E.g., in Ada: SumAll(MyLength, Sum => MySum, List =>
MyList);
8/11/2019 subprogram(robert text).ppt
10/109
Fundamentals of Subprograms
Actual/Formal Parameter
Correspondence:
2. Keyword.
Advantage: order is irrelevant
Disadvantage: user must know the formal
parameters names
8/11/2019 subprogram(robert text).ppt
11/109
Fundamentals of Subprograms
Actual/Formal Parameter Correspondence:
Default Values: in C++, Fortran 95, Ada, PHP
Ada:
procedure SORT(LIST : LIST_TYPE;LENGTH : INTEGER := 100);
...
SORT(LIST => A);
C++ default parameters must occur last in the definition
float compute_pay(float income, float tax_rate,int exemptions = 1)
8/11/2019 subprogram(robert text).ppt
12/109
Fundamentals of Subprograms
Actual/Formal Parameter Correspondence: Varying number of parameters: in C,C++, Perl, JavaScript
C:
You can have a varying number of arguments in a function(designated by ellipses: "") if you include the
library:
char *copy(char *s, ...);
There are special rules for accessing multiple arguments. See
http://www-ccs.ucsd.edu/c/stdarg.html#varying%20number%20of%20arguments
8/11/2019 subprogram(robert text).ppt
13/109
Fundamentals of Subprograms
Actual/Formal Parameter Correspondence: Varying number of parameters: in C,C++, Perl, JavaScript
C++:
You can create default arguments (must be the last parametersin the parameter list if there are mandatory parameters also).
void PrintChar(char c = '=', int n = 80)
Default parameters must appear after any mandatory
parameters
void Trouble(double z, double y, int x = 0) {
...
}
Cannot come before
mandatory parameters
8/11/2019 subprogram(robert text).ppt
14/109
Fundamentals of Subprograms
Actual/Formal Parameter Correspondence: Varying number of parameters: in C,C++, Perl, JavaScript C# can vary number but must have the same type
Use the paramsmodifier
Call sends either array or a list of expressions
If list, then expressions are placed into an array by the compiler
public void DisplayList(paramsint[ ] list){foreach (int next in list) {console.WriteLine(Next value {0}, next);
}}Myclass myObject = new Myclass;int[ ] myList = new int[6] {2, 4, 6, 8, 10, 12};myObject.DisplayList(myList);myObject.DisplayList(2, 4, 3 * x 1, 17);
8/11/2019 subprogram(robert text).ppt
15/109
Fundamentals of Subprograms
Proceduresprovide user-defined statements
Functionsprovide user-defined operators
Ada, C++, C# allow overloading operators by
defining new functions
C-based languages have only functions
Can make functions act like procedures byreturning a void
8/11/2019 subprogram(robert text).ppt
16/109
Chapter 9 Topics
Introduction
Fundamentals of Subprograms
Design Issues for Subprograms
Local Referencing Environments
Parameter-Passing Methods
Parameters that are Subprogram Names
Overloaded Subprograms
Generic Subprograms
Design Issues for Functions
User-Defined Overloaded Operators
Coroutines
8/11/2019 subprogram(robert text).ppt
17/109
Design Issues for Subprograms
1. What parameter passing methods are
provided?
2. Are parameter types checked?
3. Are local variables static or dynamic?
4. Can subprogram definitions appear in other
subprogram definitions?
8/11/2019 subprogram(robert text).ppt
18/109
Design Issues for Subprograms
5. What is the referencing environment of a
passed subprogram?
6. Can subprograms be overloaded?
7. Are subprograms allowed to be generic?
8/11/2019 subprogram(robert text).ppt
19/109
Chapter 9 Topics
Introduction
Fundamentals of Subprograms
Design Issues for Subprograms
Local Referencing Environments
Parameter-Passing Methods
Parameters that are Subprogram Names
Overloaded Subprograms
Generic Subprograms
Design Issues for Functions
User-Defined Overloaded Operators
Coroutines
8/11/2019 subprogram(robert text).ppt
20/109
Local referencing environments
If local variables are stack-dynamic:
Advantages:a. Support for recursion
b. Storage for locals is shared among some subprograms
Disadvantages:a. Allocation/deallocation time
b. Indirect addressing of local variables
Must use stack-relative addressing
c. Subprograms cannot be history sensitive Forget variable values between subprogram calls
Static locals are the opposite
8/11/2019 subprogram(robert text).ppt
21/109
Local referencing environments
Language Examples:
1. C - both (variables declared to be staticare) (default is stack dynamic)
2. Java, and Ada - dynamic only
8/11/2019 subprogram(robert text).ppt
22/109
Local referencing environments
C++
Same concept in OOP
In a method:void f()
{ static int x;
}
In a class:class C1
{
private:
static int x; // class variable
}
8/11/2019 subprogram(robert text).ppt
23/109
Chapter 9 Topics
Introduction
Fundamentals of Subprograms
Design Issues for Subprograms
Local Referencing Environments
Parameter-Passing Methods
Parameters that are Subprogram Names
Overloaded Subprograms
Generic Subprograms
Design Issues for Functions
User-Defined Overloaded Operators
Coroutines
8/11/2019 subprogram(robert text).ppt
24/109
Parameter Passing Methods
We discuss these at several different levels:
Semantic models: in mode, out mode, inout mode
In mode: can receive data from the corresponding
actual parameter
Out mode: can transmit data to the actual parameter
Inout mode: can do both
Conceptual models of transfer:
Physically move a value
Move an access path
8/11/2019 subprogram(robert text).ppt
25/109
Models of Parameter Passing
8/11/2019 subprogram(robert text).ppt
26/109
Parameter Passing Methods
Implementation Models:
1. Pass-by-value (in mode)
Value of the actual param used to initialize the
formal param. Formal parm then acts like a local variable
Either by physical move or access path
8/11/2019 subprogram(robert text).ppt
27/109
Parameter Passing Methods
Implementation Models:
1. Pass-by-value (in mode)
Disadvantages of access path method:
Must write-protect in the called subprogram Accesses cost more (indirect addressing)
Disadvantages of physical move:
Requires more storage (duplicated space)
Cost of the moves (if the parameter is large)
8/11/2019 subprogram(robert text).ppt
28/109
Parameter Passing Methods
2. Pass-by-result (out mode) Locals value is passed back to the caller
Novalue is passed into the formalparameter
Physical move (copy) is usually used If use access path get same problems as with pass-
by-value
8/11/2019 subprogram(robert text).ppt
29/109
Parameter Passing Methods
2. Pass-by-result (out mode) Disadvantages:
If value is passed, time and space
In both cases, order dependence may be a problem
e.g. in C++void sub1(int &x, int &y)
{ x = 11; y =22;}
int main(int argc, char argv[])
{ int a;
sub1(a, a)cout
8/11/2019 subprogram(robert text).ppt
30/109
Parameter Passing Methods
2. Pass-by-result (out mode) Disadvantages:
Time that actual parameter address is calculated canbe a problem
e.g.int index;
procedure sub1(y: int){
...
index++;
...
}...
sub1(list[index]);
Which address is used? Before or after call?
8/11/2019 subprogram(robert text).ppt
31/109
Parameter Passing Methods
3. Pass-by-value-result (inout mode)
Physical move, both ways
Copy into formal parameter
Then formal parameter used as local variable
Copy back into actual parameter
Also calledpass-by-copy
Disadvantages: Those of pass-by-result
Those of pass-by-value
8/11/2019 subprogram(robert text).ppt
32/109
Parameter Passing Methods
4. Pass-by-reference(inout mode)
Pass an accesspath
Also called pass-by-sharing
Advantage: passing process is efficient (no
copying and no duplicated storage)
Disadvantages:
Slower accesses (indirect access)
8/11/2019 subprogram(robert text).ppt
33/109
Parameter Passing Methods
Pass-by-reference- disadvantages (cont)
b. Allows aliasing:
i. Actual parameter collisions:
e.g.procedure sub1(a: int, b: int);...
sub1(x, x);
8/11/2019 subprogram(robert text).ppt
34/109
Parameter Passing Methods
Pass-by-reference- disadvantages (cont)
ii. Array element collisions:
e.g.
sub1(a[i], a[j]); /* if i = j */Also, sub2(a, a[i]);
Can access a[i] through both parameters
8/11/2019 subprogram(robert text).ppt
35/109
Parameter Passing Methods
Pass-by-reference- disadvantages (cont)
iii. Collision between formals and globals
void main( ) {
extern int * global;
sub(global);
}
void sub(int * param) {
extern int * global;
}
In sub,paramand globalare aliases
// defined elsewhere:
int *global;
8/11/2019 subprogram(robert text).ppt
36/109
Parameter Passing Methods
Pass-by-reference- disadvantages (cont)
Root cause of all of these is: the called subprogram
is provided wider access to nonlocals than is
necessary
Pass-by-value-result does not allow these aliases
(but has other problems!)
8/11/2019 subprogram(robert text).ppt
37/109
Parameter Passing Methods
5. Pass-by-name (multiple mode)
By textual substitution
Effect is that the nameof the actual is substitutedfor
the formal in the subprogram at the time of the call
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
8/11/2019 subprogram(robert text).ppt
38/109
Parameter Passing Methods
5. Pass-by-name (multiple mode)
Purpose: flexibility of latebinding
Late binding is important
Allows polymorphism in OOP (not as expensive aspass-by-name, however)
Lazy evaluation is late binding
Only evaluate parts of functional code when it is executed
Short-circuit evaluation of Boolean expressions
Late binding is also important in OOP e.g., virtualmethods in C++
8/11/2019 subprogram(robert text).ppt
39/109
Late binding in OOP
superclass
class C1
{
void f()
{ //some suff }
virtual void m()
{ // some stuff }
}
subclass
class C2 : C1
{
void f()
{ //override f}
virtual void m()
{ // override m}
}
C1 *x = new C1;C2 *y = new C2;
x = y; // this is legal
// y = x; illegal
X->f(); // executes the f() defined in C1
x->m(); // executes the m() defined in C2!
8/11/2019 subprogram(robert text).ppt
40/109
Parameter Passing Methods
5. Pass-by-name (multiple mode continued) Resulting semantics:
If actual is a scalar variable, it is pass-by-reference
If actual is a constant expression, it is pass-by-value
If actual is an array element, it is like nothing elsee.g.
procedure sub1(x: int; y: int);
begin
x := 1;
y := 2;x := 2;
y := 3;
end;
sub1(i, a[i]);
8/11/2019 subprogram(robert text).ppt
41/109
Parameter Passing Methods
5. Pass-by-name (multiple mode, continued) If actual is an expression with a reference to a variable that is
also accessible in the program, it is also like nothing else
e.g. (assume kis a global variable)
procedure sub1(x: int; y: int; z: int);
begin
k := 1;
y := x;
k := 5;
z := x;end;
sub1(k+1, j, i);
8/11/2019 subprogram(robert text).ppt
42/109
Pass by Name: Jensen's DeviceFamous examples of clever pass by name tricks.
real procedure sum (a, i, n);value n; integer i, n; real a;
begin
real temp;
temp := 0.0; //for 1 to n loop
for i := 1 step 1 until n do
temp := temp + a;
sum := temp; //return function value in function name
end;
s := sum(x, i, 100);s = 100 * x
s := sum(a[k], k, 100 );s = a[1] +...+ a[100]
8/11/2019 subprogram(robert text).ppt
43/109
Pass by Name: Jensen's DeviceFamous examples of clever pass by name tricks.
real procedure sum (a, i, n);
value n; integer i, n; real a;
begin
real temp;
temp := 0.0; //for 1 to n loop
for i := 1 step 1 until n do
temp := temp + a;sum := temp; //return function value in function name
end;
s := sum(a[k]*b[k], k, 100);
s = a[1]*b[1] + ... + a[100]*b[100]
s := sum(sum(a[i,j]*b[j,k], j, m), i, n);s = (a[1,1]*b[1,k] + ... + a[1,m]*b[m,k])
+ ... +
+ (a[n,1]*b[1,k] + ... + a[n,m]*b[m,k])
M and n are the dimensions of the matrix; you would enter the actualnumbers in the procedure call
8/11/2019 subprogram(robert text).ppt
44/109
Parameter Passing Methods
Disadvantages of pass by name:
Very inefficient references
Too tricky; hard to read and understand
Passing Mechanisms: Example
8/11/2019 subprogram(robert text).ppt
45/109
Passing Mechanisms: Examplevar i : integer;
a : array[1..3] of integer;
procedure T (bindingf, g : integer);
beging := g + 1;
f := 5 * i;
end;
begin
i := 2;
a[1] := 1; a[2] := 2; a[3] := 3;
t( a[i], i );
writeln( i, a[1], a[2], a[3] );
end.
binding f g i a[1] a[2] a[3]
valuevalue-result
referencename
Passing Mechanisms: Example
8/11/2019 subprogram(robert text).ppt
46/109
Passing Mechanisms: Examplevar i : integer;
a : array[1..3] of integer;
procedure T (bindingf, g : integer);
beging := g + 1;
f := 5 * i;
end;
begin
i := 2;
a[1] := 1; a[2] := 2; a[3] := 3;
t( a[i], i );
writeln( i, a[1], a[2], a[3] );
end.
binding f g i a[1] a[2] a[3]
value 10 3 2 1 2 3value-result 10 3 3 1 10 3reference ^a[2] ^i 3 1 15 3name a[i] i 3 1 2 15
8/11/2019 subprogram(robert text).ppt
47/109
Parameter Passing Methods
1. C
Pass-by-value
Achieve pass-by-reference semantics with pointers
Formals can also be constant pointers (use constkeyword)
Efficiency of passing pointers
One-way semantics of pass-by-value
Cannot modify the parameter, only use
See K&R, page 40
8/11/2019 subprogram(robert text).ppt
48/109
Parameter Passing Methods
2. C++
Like C, but also allows reference type parameters,
provide the efficiency of pass-by-reference with in-mode semantics
Reference parameters are implicitlydereferenced Reference parameters can be constant
voidfun(const int&p1, intp2, int&p3){ }
p1is pass-by-reference, but cannot be changed
8/11/2019 subprogram(robert text).ppt
49/109
Parameter Passing Methods
3. Ada
All three semantic modes are available
If out, it cannot be referenced
If in, it cannot be assigned4. Java
Like C++, all parameters are pass by value
Scalars cannot be pass-by-reference
Object values, however, are references, so effectof passing objects is pass-by-reference
8/11/2019 subprogram(robert text).ppt
50/109
Parameter Passing Methods:
Type Checking
Type checking parameters(now considered veryimportant for reliability) FORTRAN 77 and original C: none
Pascal, FORTRAN 90, Java, and Ada: always required
C89 optional
Notype checking: type checking:
double sin(x) doublesin(doublex)
doublex; { }
{ }
double value;
intcount;
value = sin(count);
First function: valid but nonsense
Second function: coerce int to float; if cant coerce, error
8/11/2019 subprogram(robert text).ppt
51/109
Implementing Parameter Passing
Implementing Parameter Passing ALGOL 60 and most of its descendants use the run-
time stack
Value- copy it to the stack; references are indirect tothe stack
Resultand value-result - same
Reference
regardless of form, put the address in the stack Access parameters by indirect reference to stack
Compiler must add code to ensure that constants passed
by reference cannot be changed.
8/11/2019 subprogram(robert text).ppt
52/109
Implementing Parameter Passing
Implementing Parameter PassingName
run-time resident code segments or subprograms
evaluate the address of the parameter;
called for each reference to the formal; these are called
thunks
Very expensive, compared to reference or value-result
8/11/2019 subprogram(robert text).ppt
53/109
Stack Implementation of
Parameter-Passing
by-value
by-result
by-value-
result
by-reference
8/11/2019 subprogram(robert text).ppt
54/109
Implementing Parameter Passing
Ada
Simple variables are passed by copy (value-result)
Structured types can be either by copy or reference
This can be a problem, becausea) Of aliases (reference allows aliases, but value-result
does not)
b) Procedure termination by error can produce different
actual parameter results
Programs with such errors are erroneous
8/11/2019 subprogram(robert text).ppt
55/109
Parameter Passing Methods
Design Considerationsfor Parameter Passing
1. Efficiency
2. One-way or two-way
These two are in conflict with one another! Good programming => limited access to variables,
which means one-way whenever possible
Efficiency => pass by reference is fastest way to
pass structures of significant size Also, functions should not allow reference
parameters
8/11/2019 subprogram(robert text).ppt
56/109
Chapter 9 Topics
Introduction
Fundamentals of Subprograms
Design Issues for Subprograms
Local Referencing Environments
Parameter-Passing Methods
Other types of parameters
Overloaded Subprograms
Generic Subprograms
Design Issues for Functions
User-Defined Overloaded Operators
Coroutines
O h f P
8/11/2019 subprogram(robert text).ppt
57/109
Other types of Parameters
Optional parameters
Arrays as parameters
Functions as parameters
O ti l P t i C
8/11/2019 subprogram(robert text).ppt
58/109
Optional Parameters in C
ANSI C and C++ (ISO standard) : choice is made by the user Must use prototype form
Can avoid type checking by replacing last part of parameterlist with ellipsis
intprintf(constchar* format_string );
Call to printf must include at least one parameter, a pointerto a character string
Can then have zero or more parameters following
Printf determines that there are more parameters by the %signs in the first parameter.
See K&R page 202 for C definition of ellipsis.
O ti l P t i C
8/11/2019 subprogram(robert text).ppt
59/109
Optional Parameters in C
ANSI C and C++: choice is made by the user ISO C defines a syntax for declaring a function to take a variable
number or type of arguments.
Such functions are referred to as varargs functions or variadic
functions.
However, the language itself provides no mechanism for such
functions to access their non-required arguments;
instead, you use the variable arguments macros defined in stdarg.h.
Seehttp://www.gnu.org/software/libc/manual/html_no
de/Variadic-Functions.html#Variadic-Functions
O ti l P t i C
8/11/2019 subprogram(robert text).ppt
60/109
Optional Parameters in C
ANSI C and C++: three steps in defining a varidic
Definethe function as variadic,
use an ellipsis (`...') in the argument list,
use special macros to access the variable arguments.
Declarethe function as variadic,
use a prototype with an ellipsis (`...'), in all the files
which call it.
Callthe function write the fixed arguments
followed by the additional variable arguments.
O ti l P t i C
8/11/2019 subprogram(robert text).ppt
61/109
Optional Parameters in C
ANSI C and C++: three steps in defining a varidic
Definethe function as variadic, must be at
least one required arg.
int func (const char *a, int b, ...);
O ti l P t i C
8/11/2019 subprogram(robert text).ppt
62/109
Optional Parameters in C
ANSI C and C++: three steps in defining a varidic
Declarethe function as variadic, using a prototype with
an ellipsis (`...'), in all the files which call it.
int func (const char *a, int b, ...)
{
body
}
To access the optional args:
The only way to access them is sequentially, in the
order they were written, you must use special macros from stdarg.h in the
following four step process:
O ti l P t i C
8/11/2019 subprogram(robert text).ppt
63/109
Optional Parameters in C
To access the optional args:
1. Initialize an argument pointer variable of type va_list usingva_start.
The argument pointer points to the first optional argument.
2. Access the optional arguments by successive calls to
va_arg.
The first call to va_arg gives you the first optional argument, the next call gives you the second, and so on.
3. Stop at any time if you wish to ignore any remaining
optional arguments.
May access fewer arguments than were supplied in the call,
will get garbage if you try to access too many arguments.
4. Indicate that you are finished with the argument pointer
variable by calling va_end.
In practice, with most C compilers, calling va_end does
nothing.
This is always true in the GNU C compiler.
O ti l P t i C
8/11/2019 subprogram(robert text).ppt
64/109
Optional Parameters in C
There is no general way for a function to determine thenumber and type of the optional arguments it was called
with.
Programmer establishes a convention for the caller to
specify the number and type of arguments.
Example: pass the number of optional arguments as one of
the fixed arguments.
This convention works provided all of the optional arguments
are of the same type.
O ti l P t i C
8/11/2019 subprogram(robert text).ppt
65/109
Optional Parameters in C
A required argument can be used as a pattern to specify both thenumber and types of the optional arguments.
The format string argument to printf is one example of this
Another possibility is to pass an end marker value as the lastoptional argument.
For example, for a function that manipulates an arbitrary number of
pointer arguments, a null pointer might indicate the end of theargument list.
The execl function works in just this way
O ti l P t i C
8/11/2019 subprogram(robert text).ppt
66/109
Optional Parameters in C
Data Type: va_list
The type va_list is used for argument pointer variables.
Macro: void va_start(va_list ap, last-required)
This macro initializes the argument pointer variable apto point to the first of the optionalarguments of the current function;
last-requiredmust be the last required argument to the function.
Macro: typeva_arg(va_list ap, type)
The va_arg macro returns the value of the next optional argument, and modifies the value ofapto point to the subsequent argument.
.The type of the value returned by va_arg is typeas specified in the call.
typemust be a self-promoting type (not char or short int or float) that matches the type of theactual argument.
Macro: void va_end(va_list ap)
This ends the use of ap. After a va_end call, further va_arg calls with the same apmay not
work.
Optional Parameters in C
8/11/2019 subprogram(robert text).ppt
67/109
Optional Parameters in C#include
#include
int add_em_up (int count,...)
{
va_listap;
int i, sum;
va_start(ap, count); /* Initialize the argument list. */
sum = 0;
for (i = 0; i < count; i++)
sum += va_arg(ap, int); /* Get the next argument value. */
va_end(ap); /* Clean up. */
return sum;
}
int main (void)
{
/* This call prints 16. */printf ("%d\n", add_em_up (3, 5, 5, 6));
/* This call prints 55. */
printf ("%d\n", add_em_up (10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
return 0;
}
Optional Parameters in Scheme
8/11/2019 subprogram(robert text).ppt
68/109
Optional Parameters in Scheme
Scheme: use a single parameter with no parenthesis
All arguments will be passed in a list(define multParam
(lambda lst
(letrec ((count
(lambda (x)(if (equal? x '())
0
(+ 1 (count (cdr x))))))
)
count lst)
))
(multParam 'a 'b 'c)
(multParam 1 2 3 4 5 6)
(multParam '() '(a b) '(c d))
Optional Parameters in Scheme
8/11/2019 subprogram(robert text).ppt
69/109
Optional Parameters in Scheme
Scheme: may combine optional and required param
First list required, then a dot and a final parameter that willcontain a list of all the multiple parameters
(define multParam2
(lambda (x y . lst)
(letrec ((count
(lambda (alst)
(if (equal? alst '())
0
(+ 1 (count (cdr alst))))))
)
(write x)
(write y)(count lst))
))
(multParam2 'a 'b 'c)
ab1
(multParam2 1 2 3 4 5 6)
12
4
(multParam2 '() '(a b) '(c d))
()(a b)1
>
Arrays as Parameters
8/11/2019 subprogram(robert text).ppt
70/109
Arrays as Parameters
MultidimensionalArraysas 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 mappingfunction
Arrays as Parameters in C/C++
8/11/2019 subprogram(robert text).ppt
71/109
Arrays as Parameters in C/C++
C and C++
Programmer is required to include the declared
sizes of all but the first subscript in the actual
parameter
This disallows writing flexible subprograms
Solution: pass a pointer to the array and the sizes
of the dimensions as other parameters; the user
must include the storage mapping function, which
is in terms of the size parameters
Arrays as Parameters: other lang
8/11/2019 subprogram(robert text).ppt
72/109
Arrays as Parameters: other lang
Ada
Constrained arrays - declared size is part of the
arrays type
Unconstrained arrays - declared size is part of the
object declaration (Java is similar)
Passing functions as parameters
8/11/2019 subprogram(robert text).ppt
73/109
Passing functionsas parameters
Issues:
1. Are parameter types checked?
Ada does notallow subprogram parameters
Java does notallow method names to be passed as
parameters C and C++ -pass pointersto functions; parameters can be
type checked
Passing functions as parameters
8/11/2019 subprogram(robert text).ppt
74/109
Passing functions as parameters
2. What is the correct referencing environment
for a subprogram that was sent as a
parameter?
Possibilities:a. It is that of the subprogram that enactedit
Shallowbinding
b. It is that of the subprogram that declaredit
Deepbinding
c. It is that of the subprogram thatpassedit
Ad hocbinding (Has neverbeen used)
Passing functions as parameters
8/11/2019 subprogram(robert text).ppt
75/109
Passing functions as parameters
For static-scopedlanguages, deepbinding is
most natural
For dynamic-scopedlanguages, shallowbinding is most natural
Passing functions as parameters
8/11/2019 subprogram(robert text).ppt
76/109
Example: sub1sub2sub3call sub4(sub2)
sub4(subx)call subx
call sub3
What is the referencing environment of sub2 when itis called in sub4? Shallow binding => sub2, sub4, sub3, sub1
Deep binding => sub2, sub1
Passing functions as parameters
Passing functions as parameters
8/11/2019 subprogram(robert text).ppt
77/109
Must use pointers to functions int (*f) ( int, float );
This is a pointer to a function fthat takestwo parameters (an int and a float) andreturns an integer.
Passing functions as parameters
in C
Passing functions as parameters
8/11/2019 subprogram(robert text).ppt
78/109
Passing functions as parameters
in C
/*** Function to search a linked list for a specific value. Arguments
** are a pointer to the first node in the list, a pointer to the
** value we're looking for, and a pointer to a function that compares
** values of the type stored on the list.
*/
#include
#include "node.h"
Node *search_list( Node *node, void const *value, int (*compare)( void const *, void const * ))
{
while( node != NULL ){
if( compare( &node->value, value ) == 0 )
break;
node = node->link;
}
return node;
}
Passing functions as parameters
8/11/2019 subprogram(robert text).ppt
79/109
(define doubler(lambda (f)
(lambda (x) (f x x))))
(define double (doubler +))
(double 13/2) 13
(double 5) 10
Passing functions as parameters
in Scheme
Chapter 9 Topics
8/11/2019 subprogram(robert text).ppt
80/109
Chapter 9 Topics
Introduction Fundamentals of Subprograms
Design Issues for Subprograms
Local Referencing Environments
Parameter-Passing Methods Other types of parameters
Overloaded Subprograms
Generic Subprograms
Design Issues for Functions User-Defined Overloaded Operators
Coroutines
Overloaded Subprograms
8/11/2019 subprogram(robert text).ppt
81/109
Overloaded Subprograms
Def: An overloaded subprogramis one thathas the same name as another subprogram in
the same referencing environment
C++ and Ada have overloaded subprograms built-in, and
users can write their own overloaded subprograms
Generic Subprograms
8/11/2019 subprogram(robert text).ppt
82/109
Generic Subprograms
A genericorpolymorphic subprogramis onethat takes parameters of different types ondifferent activations
Overloaded subprograms provide ad hoc
polymorphism
A subprogram that
takes a generic parameter that
is used in a type expression that
describes the type of the parameters of thesubprogram
provides parametric polymorphism
Generic Subprograms
8/11/2019 subprogram(robert text).ppt
83/109
Generic Subprograms
Examples of parametric polymorphism
1. Ada
Types, subscript ranges, constant values, etc., can
be generic in Ada subprograms and packages, e.g.generictype ELEMENT is private;type VECTOR is array (INTEGER range
)
of ELEMENT;procedure GENERIC_SORT(LIST: in outVECTOR);
Generic Subprograms
8/11/2019 subprogram(robert text).ppt
84/109
Generic Subprograms
procedure GENERIC_SORT(LIST: in out VECTOR)is
TEMP : ELEMENT;beginfor INDEX_1 in LIST'FIRST ..
INDEX_1'PRED(LIST'LAST) loop
for INDEX_2 in INDEX'SUCC(INDEX_1) ..LIST'LAST loop
if LIST(INDEX_1) > LIST(INDEX_2) thenTEMP := LIST (INDEX_1);LIST(INDEX_1) := LIST(INDEX_2);LIST(INDEX_2) := TEMP;
end if;end loop; -- for INDEX_1 ...
end loop; -- for INDEX_2 ...end GENERIC_SORT;
Generic Subprograms
8/11/2019 subprogram(robert text).ppt
85/109
Generic Subprograms
procedure INTEGER_SORT is new GENERIC_SORT(ELEMENT => INTEGER;
VECTOR => INT_ARRAY);
Generic Subprograms
8/11/2019 subprogram(robert text).ppt
86/109
Generic Subprograms
Ada generics are used to provide thefunctionality of parameters that are
subprograms; generic part is a subprogram
Example:generic
with function FUN(X : FLOAT) return FLOAT;
procedure INTEGRATE(LOWERBD : in FLOAT;
UPPERBD : in FLOAT;RESULT : out FLOAT);
Generic Subprograms
8/11/2019 subprogram(robert text).ppt
87/109
Generic Subprograms
procedure INTEGRATE(LOWERBD : in FLOAT;UPPERBD : in FLOAT;
RESULT : out FLOAT) is
FUNVAL : FLOAT;
begin...
FUNVAL := FUN(LOWERBD);
...
end;
INTEGRATE_FUN1 is new INTEGRATE(FUN => FUN1);
Generic Subprograms
8/11/2019 subprogram(robert text).ppt
88/109
Generic Subprograms
Examples of parametric polymorphism
2. C++
Templated functions
e.g.template
Type max(Type first, Type second) {
return first > second ? first : second;
}
Generic Subprograms
8/11/2019 subprogram(robert text).ppt
89/109
Generic Subprograms
C++ template functions are instantiatedimplicitly when the function is named in a call
or when its address is taken with the &
operator
Another example:
Generic Subprograms
8/11/2019 subprogram(robert text).ppt
90/109
Generic Subprograms
template void generic_sort(Type list[], int len) {
int top, bottom;
Type temp;
for (top = 0; top < len - 2; top++)
for (bottom = top + 1; bottom < len - 1;bottom++) {
if (list[top] > list[bottom]) {
temp = list [top];
list[top] = list[bottom];
list[bottom] = temp;
} //** end of if (list[top]...
} //** end of for (bottom = ...
} //** end of generic_sort
Generic Subprograms
8/11/2019 subprogram(robert text).ppt
91/109
Generic Subprograms
Example use:float flt_list[100];
...
generic_sort(flt_list, 100);
// Implicit instantiation
Chapter 9 Topics
8/11/2019 subprogram(robert text).ppt
92/109
Chapter 9 Topics
Introduction Fundamentals of Subprograms
Design Issues for Subprograms
Local Referencing Environments
Parameter-Passing Methods Other types of parameters
Overloaded Subprograms
Generic Subprograms
Design Issues for Functions User-Defined Overloaded Operators
Coroutines
Design Issues for Functions
8/11/2019 subprogram(robert text).ppt
93/109
Design Issues for Functions
1. Are side effects allowed?
a. Two-way parameters (Ada does not allow)
b. Nonlocal reference (all allow)
2. What types of returnvalues are allowed?
Design Issues for Functions
8/11/2019 subprogram(robert text).ppt
94/109
Design Issues for Functions
Language Examples (for possible returntypes):
1. FORTRAN, Pascal - only simple types
2. C - any type except functions and arrays
3. Ada - any type (but subprograms are not types)
4. C++ and Java - like C, but also allow classes to be
returned
Accessing Nonlocal Environments
8/11/2019 subprogram(robert text).ppt
95/109
ccess g o oca o e s
Def: The nonlocal variablesof a subprogram
are those that are visible but not declared in
the subprogram Def: Global variablesare those that may be
visible in all of the subprograms of a program
Accessing Nonlocal Environments
8/11/2019 subprogram(robert text).ppt
96/109
g
Methods:
1. FORTRAN COMMON blocks
The only way in pre-90 FORTRANs to access
nonlocal variables Can be used to share data or share storage
2. Static scoping - discussed in Chapter 5
Accessing Nonlocal Environments
8/11/2019 subprogram(robert text).ppt
97/109
g
Methods (continued):
3. External declarations - C
Subprograms are not nested
Globals are created by external declarations (they are
simply defined outside any function)
Access is by either implicit or explicit declaration
Declarations (not definitions) give types to externally
defined variables (and say they are defined elsewhere)
Accessing Nonlocal Environments
8/11/2019 subprogram(robert text).ppt
98/109
g
Methods (continued):
4. External modules - Ada
More about these later (Chapter 11)
5. Dynamic Scope - discussed in Chapter 5
8/11/2019 subprogram(robert text).ppt
99/109
Separate & Independent
8/11/2019 subprogram(robert text).ppt
100/109
p p
Compilation
Language Examples: FORTRAN II to FORTRAN 77 - independent
FORTRAN 90, Ada, C, C++, Java - separate
Pascal - allows neither
Chapter 9 Topics
8/11/2019 subprogram(robert text).ppt
101/109
p p
Introduction Fundamentals of Subprograms
Design Issues for Subprograms
Local Referencing Environments
Parameter-Passing Methods Other types of parameters
Overloaded Subprograms
Generic Subprograms
Design Issues for Functions User-Defined Overloaded Operators
Coroutines
User-Defined Overloaded
8/11/2019 subprogram(robert text).ppt
102/109
Operators
Nearly all programming languages haveoverloaded operators
Users can further overload operators in C++
and Ada (Not carried over into Java)
User-Defined Overloaded
8/11/2019 subprogram(robert text).ppt
103/109
Operators
Example (Ada) (assumeVECTOR_TYPEhas beendefined to be an array type with INTEGER elements):
function "*"(A, B : in VECTOR_TYPE)return INTEGER is
SUM : INTEGER := 0;
beginfor INDEX in A'range loopSUM := SUM + A(INDEX) * B(INDEX);
end loop;return SUM;
end "*"; Are user-defined overloaded operators good or bad?
Chapter 9 Topics
8/11/2019 subprogram(robert text).ppt
104/109
p p
Introduction Fundamentals of Subprograms
Design Issues for Subprograms
Local Referencing Environments
Parameter-Passing Methods Other types of parameters
Overloaded Subprograms
Generic Subprograms
Design Issues for Functions User-Defined Overloaded Operators
Coroutines
Coroutines
8/11/2019 subprogram(robert text).ppt
105/109
A coroutineis a subprogram that has multipleentries and controls them itself
Also called symmetric control
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
8/11/2019 subprogram(robert text).ppt
106/109
Typically, coroutines repeatedly resume eachother, possibly forever
Coroutines provide quasi-concurrent
executionof program units (the coroutines) Their execution is interleaved, but not
overlapped
Coroutines
8/11/2019 subprogram(robert text).ppt
107/109
Coroutines
8/11/2019 subprogram(robert text).ppt
108/109
Coroutines
8/11/2019 subprogram(robert text).ppt
109/109