Fundamentals of Subprograms
Fundamentals of Subprograms
Lecture #
13
Chapter 9 Subprograms
CSE 130
Lecture #
13
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
CSE 130
Lecture #
13
CSE 130
Lecture #
13
CSE 130
Lecture #
13
Advantage: order is irrelevant Disadvantage: user must know the formal parameters names not common nor commonly understood - Default Values:
e.g. procedure SORT(LIST : LIST_TYPE;
LENGTH : INTEGER := 100); ... SORT(LIST => A);
CSE 130
Lecture #
13
CSE 130
Lecture #
13
CSE 130
Lecture #
13
CSE 130
Lecture #
13
CSE 130
Lecture #
13
CSE 130
Lecture #
13
CSE 130
Lecture #
13
CSE 130
Lecture #
13
CSE 130
Lecture #
13
CSE 130
Lecture #
13
CSE 130
Lecture #
13
CSE 130
Lecture #
13
CSE 130
Lecture #
13
CSE 130
Lecture #
13
CSE 130
Lecture #
13
CSE 130
Lecture #
13
CSE 130
Lecture #
13
CSE 130
Lecture #
13
CSE 130
Lecture #
13
CSE 130
Lecture #
13
CSE 130
Lecture #
13
CSE 130
Lecture #
13
CSE 130
Lecture #
13
call sub3
CSE 130
Lecture #
13
Parameters that are Subprogram Names (Continued) What is the referencing environment of sub2 when it is called in sub4? - Shallow binding => sub2, sub4, sub3, sub1 - Deep binding => sub2, sub1 Overloaded Subprograms - Definition: 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
CSE 130
Lecture #
13
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 - Examples of parametric polymorphism 1. Ada - Types, subscript ranges, constant values, etc., can be generic in Ada subprograms and packages e.g. - see next page
10
CSE 130
Lecture #
13
CSE 130
Lecture #
13
CSE 130
Lecture #
13
11
CSE 130
Lecture #
13
CSE 130
Lecture #
13
CSE 130
Lecture #
13
User-Defined Overloaded Operators (Continued) - 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 "*";
12
CSE 130
Lecture #
13
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
13