0% found this document useful (0 votes)
200 views109 pages

Subprogram (Robert Text)

This document provides an overview of subprograms (also called procedures and functions) as covered in Chapter 9. It discusses the fundamentals of subprograms including definitions, parameter passing, and referencing environments. Parameter passing methods are covered in depth, outlining semantic models like in, out, and inout modes as well as implementation models like pass-by-value, pass-by-result, pass-by-value-result, and pass-by-reference. The document also briefly discusses design issues for subprograms and local referencing environments.

Uploaded by

Lini Ickappan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
200 views109 pages

Subprogram (Robert Text)

This document provides an overview of subprograms (also called procedures and functions) as covered in Chapter 9. It discusses the fundamentals of subprograms including definitions, parameter passing, and referencing environments. Parameter passing methods are covered in depth, outlining semantic models like in, out, and inout modes as well as implementation models like pass-by-value, pass-by-result, pass-by-value-result, and pass-by-reference. The document also briefly discusses design issues for subprograms and local referencing environments.

Uploaded by

Lini Ickappan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 109

ISBN 0-321-19362-8

Chapter 9
Subprograms
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
Introduction
Two fundamental abstraction facilities
Process abstraction (this chapter)
Data abstraction (Chapter 11)

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
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 subprogram
3. Control always returns to the caller when the
called subprograms execution terminates
Fundamentals of Subprograms
Basic definitions:
A subprogram definition is a description of the
actions of the subprogram abstraction
A subprogram call is an explicit request that the
subprogram be executed
A subprogram header is the first line of the
definition, including the name, the kind of
subprogram, and the formal parameters
The parameter profile (signature) of a subprogram
is the number, order, and types of its parameters
Fundamentals of Subprograms
Basic definitions (continued):
The protocol of a subprogram is its parameter
profile plus, if it is a function, its return type
A subprogram declaration provides the protocol,
but not the body, of the subprogram (called
function prototypes in C/C++)
Java and C# do not use subprogram declarations
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
Fundamentals of Subprograms
Access to data in subprogram
Global variables (dangerous)
Parameters
Formal parameters. The parameters in the
subprogram header.
Actual parameters. The parameters used in
the subprogram call.
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);
Fundamentals of Subprograms
Actual/Formal Parameter
Correspondence:
2. Keyword.
Advantage: order is irrelevant
Disadvantage: user must know the formal
parameters names
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)
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 <stdarg.h>
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
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 parameters
in 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
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 params modifier
Call sends either array or a list of expressions
If list, then expressions are placed into an array by the compiler

public void DisplayList(params int[ ] 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);
Fundamentals of Subprograms
Procedures provide user-defined statements
Functions provide 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 by
returning a void
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
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?
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?

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
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
Local referencing environments
Language Examples:
1. C - both (variables declared to be static
are) (default is stack dynamic)
2. Java, and Ada - dynamic only
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
}
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
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
Models of Parameter Passing
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
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)
Parameter Passing Methods
2. Pass-by-result (out mode)
Locals value is passed back to the caller
No value is passed into the formal parameter
Physical move (copy) is usually used
If use access path get same problems as with pass-
by-value
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 << a; // whats in a?
}
Value of x in the caller depends on order of assignments at
the return; last formal copied out is the value of x
Parameter Passing Methods
2. Pass-by-result (out mode)
Disadvantages:
Time that actual parameter address is calculated can
be a problem
e.g.
int index;
procedure sub1(y: int){
...
index++;
...
}
...
sub1(list[index]);
Which address is used? Before or after call?
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 called pass-by-copy
Disadvantages:
Those of pass-by-result
Those of pass-by-value
Parameter Passing Methods
4. 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 (indirect access)
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);
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
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, param and global are aliases

// defined elsewhere:
int *global;
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!)
Parameter Passing Methods
5. Pass-by-name (multiple mode)
By textual substitution
Effect is that the name of the actual is substituted for
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

Parameter Passing Methods
5. Pass-by-name (multiple mode)
Purpose: flexibility of late binding
Late binding is important
Allows polymorphism in OOP (not as expensive as
pass-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., virtual methods in C++
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!
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 else
e.g.
procedure sub1(x: int; y: int);
begin
x := 1;
y := 2;
x := 2;
y := 3;
end;
sub1(i, a[i]);
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 k is 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);
Pass by Name: Jensen's Device
Famous 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]
Pass by Name: Jensen's Device
Famous 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 actual
numbers in the procedure call
Parameter Passing Methods
Disadvantages of pass by name:
Very inefficient references
Too tricky; hard to read and understand
Passing Mechanisms: Example
var i : integer;
a : array[1..3] of integer;
procedure T (binding f, g : integer);
begin
g := 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
value-result
reference
name
Passing Mechanisms: Example
var i : integer;
a : array[1..3] of integer;
procedure T (binding f, g : integer);
begin
g := 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 3
value-result 10 3 3 1 10 3
reference ^a[2] ^i 3 1 15 3
name a[i] i 3 1 2 15
Parameter Passing Methods
1. C
Pass-by-value
Achieve pass-by-reference semantics with pointers
Formals can also be constant pointers (use const
keyword)
Efficiency of passing pointers
One-way semantics of pass-by-value
Cannot modify the parameter, only use
See K&R, page 40
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 implicitly dereferenced
Reference parameters can be constant
void fun(const int &p1, int p2, int &p3)
{ }
p1 is pass-by-reference, but cannot be changed
Parameter Passing Methods
3. Ada
All three semantic modes are available
If out, it cannot be referenced
If in, it cannot be assigned
4. Java
Like C++, all parameters are pass by value
Scalars cannot be pass-by-reference
Object values, however, are references, so effect
of passing objects is pass-by-reference
Parameter Passing Methods:
Type Checking
Type checking parameters (now considered very
important for reliability)
FORTRAN 77 and original C: none
Pascal, FORTRAN 90, Java, and Ada: always required
C89 optional
No type checking: type checking:
double sin(x) double sin(double x)
double x; { }
{ }
double value;
int count;
value = sin(count);
First function: valid but nonsense
Second function: coerce int to float; if cant coerce, error
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 to
the stack
Result and 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.

Implementing Parameter Passing
Implementing Parameter Passing
Name
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
Stack Implementation of
Parameter-Passing
by-value
by-result
by-value-
result
by-reference
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, because
a) 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
Parameter Passing Methods
Design Considerations for 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
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
Other types of Parameters
Optional parameters
Arrays as parameters
Functions as parameters

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 parameter
list with ellipsis

int printf(const char* format_string );

Call to printf must include at least one parameter, a pointer
to 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.

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.
See
http://www.gnu.org/software/libc/manual/html_no
de/Variadic-Functions.html#Variadic-Functions
Optional Parameters in C
ANSI C and C++: three steps in defining a varidic
Define the function as variadic,
use an ellipsis (`...') in the argument list,
use special macros to access the variable arguments.

Declare the function as variadic,
use a prototype with an ellipsis (`...'), in all the files
which call it.

Call the function
write the fixed arguments
followed by the additional variable arguments.
Optional Parameters in C
ANSI C and C++: three steps in defining a varidic
Define the function as variadic, must be at
least one required arg.

int func (const char *a, int b, ...);


Optional Parameters in C
ANSI C and C++: three steps in defining a varidic
Declare the 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:
Optional Parameters in C
To access the optional args:
1. Initialize an argument pointer variable of type va_list using
va_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.
Optional Parameters in C
There is no general way for a function to determine the
number 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.

Optional Parameters in C
A required argument can be used as a pattern to specify both the
number 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 last
optional argument.
For example, for a function that manipulates an arbitrary number of
pointer arguments, a null pointer might indicate the end of the
argument list.
The execl function works in just this way
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 ap to point to the first of the optional
arguments of the current function;
last-required must be the last required argument to the function.
Macro: type va_arg (va_list ap, type)
The va_arg macro returns the value of the next optional argument, and modifies the value of
ap to point to the subsequent argument.
.The type of the value returned by va_arg is type as specified in the call.
type must be a self-promoting type (not char or short int or float) that matches the type of the
actual 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 ap may not
work.
Optional Parameters in C
#include <stdarg.h>
#include <stdio.h>

int add_em_up (int count,...)
{
va_list ap;
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
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
Scheme: may combine optional and required param
First list required, then a dot and a final parameter that will
contain 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)
ab
1
(multParam2 1 2 3 4 5 6)
12
4
(multParam2 '() '(a b) '(c d))
()(a b)
1
>
Arrays as Parameters
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
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
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
Issues:
1. Are parameter types checked?
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
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 enacted it
Shallow binding
b. It is that of the subprogram that declared it
Deep binding
c. It is that of the subprogram that passed it
Ad hoc binding (Has never been used)
Passing functions as parameters
For static-scoped languages, deep binding is
most natural
For dynamic-scoped languages, shallow
binding is most natural
Example: sub1
sub2
sub3
call sub4(sub2)
sub4(subx)
call subx

call sub3
What is the referencing environment of sub2 when it
is called in sub4?
Shallow binding => sub2, sub4, sub3, sub1
Deep binding => sub2, sub1
Passing functions as parameters
Must use pointers to functions
int (*f) ( int, float );
This is a pointer to a function f that takes
two parameters (an int and a float) and
returns an integer.
Passing functions as parameters
in C
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 <stdio.h>
#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;
}
(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
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
Def: An overloaded subprogram is one that
has 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
A generic or polymorphic subprogram is one
that takes parameters of different types on
different 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 the
subprogram
provides parametric polymorphism
Generic Subprograms
Examples of parametric polymorphism
1. Ada
Types, subscript ranges, constant values, etc., can
be generic in Ada subprograms and packages, e.g.
generic
type ELEMENT is private;
type VECTOR is array (INTEGER range
<>)
of ELEMENT;
procedure GENERIC_SORT(LIST: in out
VECTOR);
Generic Subprograms
procedure GENERIC_SORT(LIST: in out VECTOR)
is
TEMP : ELEMENT;
begin
for 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) then
TEMP := 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
procedure INTEGER_SORT is new GENERIC_SORT(
ELEMENT => INTEGER;
VECTOR => INT_ARRAY);
Generic Subprograms
Ada generics are used to provide the
functionality 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
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
Examples of parametric polymorphism
2. C++
Templated functions
e.g.
template <class Type>
Type max(Type first, Type second) {
return first > second ? first : second;
}

Generic Subprograms
C++ template functions are instantiated
implicitly when the function is named in a call
or when its address is taken with the &
operator
Another example:
Generic Subprograms
template <class Type>
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
Example use:
float flt_list[100];
...
generic_sort(flt_list, 100);
// Implicit instantiation

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
1. Are side effects allowed?
a. Two-way parameters (Ada does not allow)
b. Nonlocal reference (all allow)
2. What types of return values are allowed?
Design Issues for Functions
Language Examples (for possible return
types):
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
Def: The nonlocal variables of a subprogram
are those that are visible but not declared in
the subprogram
Def: Global variables are those that may be
visible in all of the subprograms of a program
Accessing Nonlocal Environments
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
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
Methods (continued):
4. External modules - Ada
More about these later (Chapter 11)
5. Dynamic Scope - discussed in Chapter 5
Separate & Independent
Compilation
Def: Independent compilation is compilation
of some of the units of a program separately
from the rest of the program, without the
benefit of interface information
Def: Separate compilation is compilation of
some of the units of a program separately
from the rest of the program, using interface
information to check the correctness of the
interface between the two parts.
Separate & Independent
Compilation
Language Examples:
FORTRAN II to FORTRAN 77 - independent
FORTRAN 90, Ada, C, C++, Java - separate
Pascal - allows neither

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
User-Defined Overloaded
Operators
Nearly all programming languages have
overloaded operators
Users can further overload operators in C++
and Ada (Not carried over into Java)
User-Defined Overloaded
Operators
Example (Ada) (assume VECTOR_TYPE has been
defined to be an array type with INTEGER elements):
function "*"(A, B : in VECTOR_TYPE)
return INTEGER is
SUM : INTEGER := 0;
begin
for INDEX in A'range loop
SUM := SUM + A(INDEX) * B(INDEX);
end loop;
return SUM;
end "*";
Are user-defined overloaded operators good or bad?

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
Coroutines
A coroutine is a subprogram that has multiple
entries 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
Typically, coroutines repeatedly resume each
other, possibly forever
Coroutines provide quasi-concurrent
execution of program units (the coroutines)
Their execution is interleaved, but not
overlapped
Coroutines
Coroutines
Coroutines

You might also like