SlideShare una empresa de Scribd logo
1 de 17
ICS 313 - Fundamentals of Programming Languages 1
9. Subprograms
9.2 Fundamentals of Subprograms
General characteristics of subprograms
A subprogram has a single entry point
The caller is suspended during execution of the called subprogram
Control always returns to the caller when the called subprogram’s
execution terminates
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 of a subprogram is the number, order, and types of
its parameters
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
ICS 313 - Fundamentals of Programming Languages 2
9.2 Fundamentals of Subprograms (continued)
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
Actual/Formal Parameter Correspondence
Positional
Keyword
e.g. SORT(LIST => A, LENGTH => N);
Advantage: order is irrelevant
Disadvantage: user must know the formal parameter’s names
Default Values:
e.g.
procedure SORT(LIST : LIST_TYPE; LENGTH : INTEGER := 100);
...
SORT(LIST => A);
Procedures provide user-defined statements
Functions provide user-defined operators
9.3 Design Issues for Subprograms
What parameter passing methods are provided?
Are parameter types checked?
Are local variables static or dynamic?
What is the referencing environment of a passed subprogram?
Are parameter types in passed subprograms checked?
Can subprogram definitions be nested?
Can subprograms be overloaded?
Are subprograms allowed to be generic?
Is separate or independent compilation supported?
ICS 313 - Fundamentals of Programming Languages 3
9.4 Local referencing environments
If local variables are stack-dynamic:
Advantages
Support for recursion
Storage for locals is shared among some subprograms
Disadvantages
Allocation/deallocation time
Indirect addressing
Subprograms cannot be history sensitive
Static locals are the opposite
Language Examples
FORTRAN 77 and 90 - most are static, but the implementor can
choose either
(User can force static with SAVE)
C - both (variables declared to be static are)
(default is stack dynamic)
Pascal, Java, and Ada - dynamic only
9.5 Parameter Passing Methods
We discuss these at several different levels
Semantic Models: in mode, out mode, inout mode
Conceptual Models of Transfer
Physically move a value
Move an access path
ICS 313 - Fundamentals of Programming Languages 4
9.5 Parameter Passing Methods (continued)
Implementation Models
Pass-by-value (in mode)
Either by physical move or access path
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)
9.5 Parameter Passing Methods (continued)
Pass-by-result (out mode)
Local’s value is passed back to the caller
Physical move is usually used
Disadvantages:
If value is passed, time and space
In both cases, order dependence may be a problem
e.g.
procedure sub1(y: int, z: int);
...
sub1(x, x);
Value of x in the caller depends on order of assignments at the return
Pass-by-value-result (inout mode)
Physical move, both ways
Also called pass-by-copy
Disadvantages:
Those of pass-by-result
Those of pass-by-value
ICS 313 - Fundamentals of Programming Languages 5
9.5 Parameter Passing Methods (continued)
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
Allows aliasing
Actual parameter collisions
e.g. procedure sub1(a: int, b: int);
...
sub1(x, x);
Array element collisions
e.g.
sub1(a[i], a[j]); /* if i = j */
Also, sub2(a, a[i]); (a different one)
Collision between formals and globals
– 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!)
9.5 Parameter Passing Methods (continued)
Pass-by-name (multiple 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
Purpose: flexibility of late binding
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]);
ICS 313 - Fundamentals of Programming Languages 6
9.5 Parameter Passing Methods (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);
Disadvantages of pass by name
Very inefficient references
Too tricky; hard to read and understand
9.5 Parameter Passing Methods (continued)
Language Examples
FORTRAN
Before 77, pass-by-reference
77 - scalar variables are often passed by value-result
ALGOL 60
Pass-by-name is default; pass-by-value is optional
ALGOL W
Pass-by-value-result
C
Pass-by-value
Pascal and Modula-2
Default is pass-by-value; pass-by-reference is optional
C++
Like C, but also allows reference type parameters, which provide the efficiency of
pass-by-reference with in-mode semantics
ICS 313 - Fundamentals of Programming Languages 7
9.5 Parameter Passing Methods (continued)
Ada
All three semantic modes are available
If out, it cannot be referenced
If in, it cannot be assigned
Java
Like C++, except only references
Type checking parameters
(Now considered very important for reliability)
FORTRAN 77 and original C: none
Pascal, FORTRAN 90, Java, and Ada: it is always
required
ANSI C and C++: choice is made by the user
9.5 Parameter Passing Methods (continued)
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 - same
Reference - regardless of form, put the address in the stack
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
ICS 313 - Fundamentals of Programming Languages 8
9.5 Parameter Passing Methods (continued)
One possible stack implementation of the common parameter-passing methods
9.5 Parameter Passing Methods (continued)
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”
ICS 313 - Fundamentals of Programming Languages 9
9.5 Parameter Passing Methods (continued)
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
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 (See example, p. 371)
Pascal
Not a problem (declared size is part of the array’s type)
Ada
Constrained arrays - like Pascal
Unconstrained arrays - declared size is part of the object declaration
(See example p. 371)
(Java is similar)
9.5 Parameter Passing Methods (continued)
Pre-90 FORTRAN
Formal parameter declarations for arrays can include passed parameters
e.g.
SUBPROGRAM SUB(MATRIX, ROWS, COLS, RESULT)
INTEGER ROWS, COLS
REAL MATRIX (ROWS, COLS), RESULT
...
END
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
ICS 313 - Fundamentals of Programming Languages 10
9.6 Parameters that are Subprogram Names
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?
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)
9.6 Parameters that are Subprogram Names
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
ICS 313 - Fundamentals of Programming Languages 11
9.7 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
9.8 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
Ada
Types, subscript ranges, constant values, etc., can be generic
in Ada subprograms and packages e.g. - see next page
ICS 313 - Fundamentals of Programming Languages 12
9.8 Generic Subprograms (continued)
generic
type ELEMENT is private;
type VECTOR is array (INTEGER range <>) of ELEMENT;
procedure GENERIC_SORT(LIST: in out VECTOR);
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;
procedure INTEGER_SORT is new GENERIC_SORT(ELEMENT => INTEGER; VECTOR => INT_ARRAY);
9.8 Generic Subprograms (continued)
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);
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);
ICS 313 - Fundamentals of Programming Languages 13
9.8 Generic Subprograms (continued)
C++
Templated functions
e.g.
template <class Type>
Type max(Type first, Type second) {
return first > second ? first : second;
}
C++ template functions are instantiated implicitly when the function
is named in a call or when its address is taken with the & operator
9.8 Generic Subprograms (continued)
Another example:
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 for (bottom = ...
} //** end of generic_sort
Example use:
float flt_list[100];
...
generic_sort(flt_list, 100); // Implicit
// instantiation
ICS 313 - Fundamentals of Programming Languages 14
9.9 Separate & Independent Compilation
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
Separate compilation is compilation of some of the units of a
program separately from the rest of the program, using
interface nformation to check the correctness of the interface
between the two parts
Language Examples:
FORTRAN II to FORTRAN 77 - independent
FORTRAN 90, Ada, C++, Java - separate
Pascal - allows neither
9.10 Design Issues for Functions
Are side effects allowed?
Two-way parameters (Ada does not allow)
Nonlocal reference (all allow)
What types of return values are allowed?
Language Examples (for possible return types):
FORTRAN, Pascal - only simple types
C - any type except functions and arrays
Ada - any type (but subprograms are not types)
C++ and Java - like C, but also allow classes to be returned
ICS 313 - Fundamentals of Programming Languages 15
9.11 Accessing Nonlocal Environments
The nonlocal variables of a subprogram
are those that are visible but not declared
in the subprogram
Global variables are those that may be
visible in all of the subprograms of a
program
Methods:
1. FORTRAN COMMON
The only way in pre-90 FORTRANs to access nonlocal
variables
Can be used to share data or share storage
9.11 Accessing Nonlocal Environments (continued)
2. Static scoping - discussed in Chapter 5
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)
4. External modules - Ada
More about these later (Chapter 11)
5. Dynamic Scope - discussed in Chapter 5
ICS 313 - Fundamentals of Programming Languages 16
9.12 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)
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?
9.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
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
ICS 313 - Fundamentals of Programming Languages 17
9.13 Coroutines (continued)
Examples

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

Subprogram
SubprogramSubprogram
Subprogram
 
Unit 5
Unit 5Unit 5
Unit 5
 
Unit1 principle of programming language
Unit1 principle of programming languageUnit1 principle of programming language
Unit1 principle of programming language
 
Primitive data types
Primitive data typesPrimitive data types
Primitive data types
 
Scope - Static and Dynamic
Scope - Static and DynamicScope - Static and Dynamic
Scope - Static and Dynamic
 
Unit 2
Unit 2Unit 2
Unit 2
 
Implicit and explicit sequence control with exception handling
Implicit and explicit sequence control with exception handlingImplicit and explicit sequence control with exception handling
Implicit and explicit sequence control with exception handling
 
9. control statement
9. control statement9. control statement
9. control statement
 
Compiler Construction
Compiler ConstructionCompiler Construction
Compiler Construction
 
Compiler Design
Compiler DesignCompiler Design
Compiler Design
 
Different phases of a compiler
Different phases of a compilerDifferent phases of a compiler
Different phases of a compiler
 
Structure of the compiler
Structure of the compilerStructure of the compiler
Structure of the compiler
 
Type checking in compiler design
Type checking in compiler designType checking in compiler design
Type checking in compiler design
 
what is compiler and five phases of compiler
what is compiler and five phases of compilerwhat is compiler and five phases of compiler
what is compiler and five phases of compiler
 
Unit 5 cspc
Unit 5 cspcUnit 5 cspc
Unit 5 cspc
 
Unit 1 cd
Unit 1 cdUnit 1 cd
Unit 1 cd
 
phases of a compiler
 phases of a compiler phases of a compiler
phases of a compiler
 
Compiler Construction
Compiler ConstructionCompiler Construction
Compiler Construction
 
phases of compiler-analysis phase
phases of compiler-analysis phasephases of compiler-analysis phase
phases of compiler-analysis phase
 
Cd unit i
Cd unit iCd unit i
Cd unit i
 

Destacado

Generics in .NET, C++ and Java
Generics in .NET, C++ and JavaGenerics in .NET, C++ and Java
Generics in .NET, C++ and JavaSasha Goldshtein
 
Auteursrecht in academische omgeving: DPO Professionaliseringsbijeenkomst, 23...
Auteursrecht in academische omgeving: DPO Professionaliseringsbijeenkomst, 23...Auteursrecht in academische omgeving: DPO Professionaliseringsbijeenkomst, 23...
Auteursrecht in academische omgeving: DPO Professionaliseringsbijeenkomst, 23...Leon Osinski
 
A basic course on Research data management: part 1 - part 4
A basic course on Research data management: part 1 - part 4A basic course on Research data management: part 1 - part 4
A basic course on Research data management: part 1 - part 4Leon Osinski
 
3963066 pl-sql-notes-only
3963066 pl-sql-notes-only3963066 pl-sql-notes-only
3963066 pl-sql-notes-onlyAshwin Kumar
 
Oracle database 12c sql worshop 1 activity guide
Oracle database 12c sql worshop 1 activity guideOracle database 12c sql worshop 1 activity guide
Oracle database 12c sql worshop 1 activity guideOtto Paiz
 
16 logical programming
16 logical programming16 logical programming
16 logical programmingjigeno
 
Ppl for students unit 1,2 and 3
Ppl for students unit 1,2 and 3Ppl for students unit 1,2 and 3
Ppl for students unit 1,2 and 3Akshay Nagpurkar
 
48742447 11g-sql-fundamentals-ii-additional-practices-and-solutions
48742447 11g-sql-fundamentals-ii-additional-practices-and-solutions48742447 11g-sql-fundamentals-ii-additional-practices-and-solutions
48742447 11g-sql-fundamentals-ii-additional-practices-and-solutionsAshwin Kumar
 
Software engineering lecture notes
Software engineering lecture notesSoftware engineering lecture notes
Software engineering lecture notesSiva Ayyakutti
 
Free PMP notes,Free PMP Study Material,Free PMP Chapter wise notes,PMP Exam N...
Free PMP notes,Free PMP Study Material,Free PMP Chapter wise notes,PMP Exam N...Free PMP notes,Free PMP Study Material,Free PMP Chapter wise notes,PMP Exam N...
Free PMP notes,Free PMP Study Material,Free PMP Chapter wise notes,PMP Exam N...TURKI , PMP
 
Presentation on 1G/2G/3G/4G/5G/Cellular & Wireless Technologies
Presentation on 1G/2G/3G/4G/5G/Cellular & Wireless TechnologiesPresentation on 1G/2G/3G/4G/5G/Cellular & Wireless Technologies
Presentation on 1G/2G/3G/4G/5G/Cellular & Wireless TechnologiesKaushal Kaith
 

Destacado (20)

Generics in .NET, C++ and Java
Generics in .NET, C++ and JavaGenerics in .NET, C++ and Java
Generics in .NET, C++ and Java
 
Oops
OopsOops
Oops
 
Auteursrecht in academische omgeving: DPO Professionaliseringsbijeenkomst, 23...
Auteursrecht in academische omgeving: DPO Professionaliseringsbijeenkomst, 23...Auteursrecht in academische omgeving: DPO Professionaliseringsbijeenkomst, 23...
Auteursrecht in academische omgeving: DPO Professionaliseringsbijeenkomst, 23...
 
Collections in-csharp
Collections in-csharpCollections in-csharp
Collections in-csharp
 
Raspuns MS Subprogram FIV 2016
Raspuns MS Subprogram FIV 2016Raspuns MS Subprogram FIV 2016
Raspuns MS Subprogram FIV 2016
 
A basic course on Research data management: part 1 - part 4
A basic course on Research data management: part 1 - part 4A basic course on Research data management: part 1 - part 4
A basic course on Research data management: part 1 - part 4
 
Abstract data types
Abstract data typesAbstract data types
Abstract data types
 
3963066 pl-sql-notes-only
3963066 pl-sql-notes-only3963066 pl-sql-notes-only
3963066 pl-sql-notes-only
 
16 exception handling - i
16 exception handling - i16 exception handling - i
16 exception handling - i
 
Oracle database 12c sql worshop 1 activity guide
Oracle database 12c sql worshop 1 activity guideOracle database 12c sql worshop 1 activity guide
Oracle database 12c sql worshop 1 activity guide
 
16 logical programming
16 logical programming16 logical programming
16 logical programming
 
C# Generics
C# GenericsC# Generics
C# Generics
 
Delegates and events
Delegates and events   Delegates and events
Delegates and events
 
Ppl for students unit 1,2 and 3
Ppl for students unit 1,2 and 3Ppl for students unit 1,2 and 3
Ppl for students unit 1,2 and 3
 
48742447 11g-sql-fundamentals-ii-additional-practices-and-solutions
48742447 11g-sql-fundamentals-ii-additional-practices-and-solutions48742447 11g-sql-fundamentals-ii-additional-practices-and-solutions
48742447 11g-sql-fundamentals-ii-additional-practices-and-solutions
 
Software engineering lecture notes
Software engineering lecture notesSoftware engineering lecture notes
Software engineering lecture notes
 
Free PMP notes,Free PMP Study Material,Free PMP Chapter wise notes,PMP Exam N...
Free PMP notes,Free PMP Study Material,Free PMP Chapter wise notes,PMP Exam N...Free PMP notes,Free PMP Study Material,Free PMP Chapter wise notes,PMP Exam N...
Free PMP notes,Free PMP Study Material,Free PMP Chapter wise notes,PMP Exam N...
 
E-Commerce PPT
E-Commerce PPTE-Commerce PPT
E-Commerce PPT
 
E commerce
E commerceE commerce
E commerce
 
Presentation on 1G/2G/3G/4G/5G/Cellular & Wireless Technologies
Presentation on 1G/2G/3G/4G/5G/Cellular & Wireless TechnologiesPresentation on 1G/2G/3G/4G/5G/Cellular & Wireless Technologies
Presentation on 1G/2G/3G/4G/5G/Cellular & Wireless Technologies
 

Similar a 9 subprograms

Improved Developer Productivity In JDK8
Improved Developer Productivity In JDK8Improved Developer Productivity In JDK8
Improved Developer Productivity In JDK8Simon Ritter
 
Java findamentals2
Java findamentals2Java findamentals2
Java findamentals2Todor Kolev
 
Java findamentals2
Java findamentals2Java findamentals2
Java findamentals2Todor Kolev
 
Lecture2_MCS4_Evening.pptx
Lecture2_MCS4_Evening.pptxLecture2_MCS4_Evening.pptx
Lecture2_MCS4_Evening.pptxSaqlainYaqub1
 
imperative programming language, java, android
imperative programming language, java, androidimperative programming language, java, android
imperative programming language, java, androidi i
 
Patterns in Python
Patterns in PythonPatterns in Python
Patterns in Pythondn
 
C#3.0 & Vb 9.0 New Features
C#3.0 & Vb 9.0 New FeaturesC#3.0 & Vb 9.0 New Features
C#3.0 & Vb 9.0 New Featurestechfreak
 
Java 8 lambdas expressions
Java 8 lambdas expressionsJava 8 lambdas expressions
Java 8 lambdas expressionsLars Lemos
 
systemverilog-interview-questions.docx
systemverilog-interview-questions.docxsystemverilog-interview-questions.docx
systemverilog-interview-questions.docxssuser1c8ca21
 
Chapter 9 & chapter 10 solutions
Chapter 9 & chapter 10 solutionsChapter 9 & chapter 10 solutions
Chapter 9 & chapter 10 solutionsSaeed Iqbal
 
Java 8 - A step closer to Parallelism
Java 8 - A step closer to ParallelismJava 8 - A step closer to Parallelism
Java 8 - A step closer to Parallelismjbugkorea
 
ParaSail
ParaSail  ParaSail
ParaSail AdaCore
 
Evaluate And Analysis of ALGOL, ADA ,PASCAL Programming Languages
Evaluate And Analysis of ALGOL, ADA ,PASCAL Programming Languages Evaluate And Analysis of ALGOL, ADA ,PASCAL Programming Languages
Evaluate And Analysis of ALGOL, ADA ,PASCAL Programming Languages Charitha Gamage
 
GenePattern: Ted Liefeld
GenePattern: Ted LiefeldGenePattern: Ted Liefeld
GenePattern: Ted Liefeldniranabey
 

Similar a 9 subprograms (20)

Improved Developer Productivity In JDK8
Improved Developer Productivity In JDK8Improved Developer Productivity In JDK8
Improved Developer Productivity In JDK8
 
14274730 (1).ppt
14274730 (1).ppt14274730 (1).ppt
14274730 (1).ppt
 
Java findamentals2
Java findamentals2Java findamentals2
Java findamentals2
 
Java findamentals2
Java findamentals2Java findamentals2
Java findamentals2
 
Lecture2_MCS4_Evening.pptx
Lecture2_MCS4_Evening.pptxLecture2_MCS4_Evening.pptx
Lecture2_MCS4_Evening.pptx
 
imperative programming language, java, android
imperative programming language, java, androidimperative programming language, java, android
imperative programming language, java, android
 
Subprogramms
SubprogrammsSubprogramms
Subprogramms
 
Unit 1
Unit  1Unit  1
Unit 1
 
Patterns in Python
Patterns in PythonPatterns in Python
Patterns in Python
 
Colloquium Report
Colloquium ReportColloquium Report
Colloquium Report
 
C#3.0 & Vb 9.0 New Features
C#3.0 & Vb 9.0 New FeaturesC#3.0 & Vb 9.0 New Features
C#3.0 & Vb 9.0 New Features
 
Java 8 lambdas expressions
Java 8 lambdas expressionsJava 8 lambdas expressions
Java 8 lambdas expressions
 
systemverilog-interview-questions.docx
systemverilog-interview-questions.docxsystemverilog-interview-questions.docx
systemverilog-interview-questions.docx
 
Chapter 9 & chapter 10 solutions
Chapter 9 & chapter 10 solutionsChapter 9 & chapter 10 solutions
Chapter 9 & chapter 10 solutions
 
Java 8 - A step closer to Parallelism
Java 8 - A step closer to ParallelismJava 8 - A step closer to Parallelism
Java 8 - A step closer to Parallelism
 
C language 3
C language 3C language 3
C language 3
 
Annotations
AnnotationsAnnotations
Annotations
 
ParaSail
ParaSail  ParaSail
ParaSail
 
Evaluate And Analysis of ALGOL, ADA ,PASCAL Programming Languages
Evaluate And Analysis of ALGOL, ADA ,PASCAL Programming Languages Evaluate And Analysis of ALGOL, ADA ,PASCAL Programming Languages
Evaluate And Analysis of ALGOL, ADA ,PASCAL Programming Languages
 
GenePattern: Ted Liefeld
GenePattern: Ted LiefeldGenePattern: Ted Liefeld
GenePattern: Ted Liefeld
 

Más de jigeno

Access2007 part1
Access2007 part1Access2007 part1
Access2007 part1jigeno
 
Basic introduction to ms access
Basic introduction to ms accessBasic introduction to ms access
Basic introduction to ms accessjigeno
 
15 functional programming
15 functional programming15 functional programming
15 functional programmingjigeno
 
15 functional programming
15 functional programming15 functional programming
15 functional programmingjigeno
 
14 exception handling
14 exception handling14 exception handling
14 exception handlingjigeno
 
13 concurrency
13 concurrency13 concurrency
13 concurrencyjigeno
 
12 object oriented programming
12 object oriented programming12 object oriented programming
12 object oriented programmingjigeno
 
11 abstract data types
11 abstract data types11 abstract data types
11 abstract data typesjigeno
 
8 statement-level control structure
8 statement-level control structure8 statement-level control structure
8 statement-level control structurejigeno
 
7 expressions and assignment statements
7 expressions and assignment statements7 expressions and assignment statements
7 expressions and assignment statementsjigeno
 
6 data types
6 data types6 data types
6 data typesjigeno
 
5 names
5 names5 names
5 namesjigeno
 
4 lexical and syntax analysis
4 lexical and syntax analysis4 lexical and syntax analysis
4 lexical and syntax analysisjigeno
 
3 describing syntax and semantics
3 describing syntax and semantics3 describing syntax and semantics
3 describing syntax and semanticsjigeno
 
2 evolution of the major programming languages
2 evolution of the major programming languages2 evolution of the major programming languages
2 evolution of the major programming languagesjigeno
 
1 preliminaries
1 preliminaries1 preliminaries
1 preliminariesjigeno
 
Access2007 m2
Access2007 m2Access2007 m2
Access2007 m2jigeno
 
Access2007 m1
Access2007 m1Access2007 m1
Access2007 m1jigeno
 

Más de jigeno (19)

Access2007 part1
Access2007 part1Access2007 part1
Access2007 part1
 
Basic introduction to ms access
Basic introduction to ms accessBasic introduction to ms access
Basic introduction to ms access
 
Bsit1
Bsit1Bsit1
Bsit1
 
15 functional programming
15 functional programming15 functional programming
15 functional programming
 
15 functional programming
15 functional programming15 functional programming
15 functional programming
 
14 exception handling
14 exception handling14 exception handling
14 exception handling
 
13 concurrency
13 concurrency13 concurrency
13 concurrency
 
12 object oriented programming
12 object oriented programming12 object oriented programming
12 object oriented programming
 
11 abstract data types
11 abstract data types11 abstract data types
11 abstract data types
 
8 statement-level control structure
8 statement-level control structure8 statement-level control structure
8 statement-level control structure
 
7 expressions and assignment statements
7 expressions and assignment statements7 expressions and assignment statements
7 expressions and assignment statements
 
6 data types
6 data types6 data types
6 data types
 
5 names
5 names5 names
5 names
 
4 lexical and syntax analysis
4 lexical and syntax analysis4 lexical and syntax analysis
4 lexical and syntax analysis
 
3 describing syntax and semantics
3 describing syntax and semantics3 describing syntax and semantics
3 describing syntax and semantics
 
2 evolution of the major programming languages
2 evolution of the major programming languages2 evolution of the major programming languages
2 evolution of the major programming languages
 
1 preliminaries
1 preliminaries1 preliminaries
1 preliminaries
 
Access2007 m2
Access2007 m2Access2007 m2
Access2007 m2
 
Access2007 m1
Access2007 m1Access2007 m1
Access2007 m1
 

Último

Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 

Último (20)

Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 

9 subprograms

  • 1. ICS 313 - Fundamentals of Programming Languages 1 9. Subprograms 9.2 Fundamentals of Subprograms General characteristics of subprograms A subprogram has a single entry point The caller is suspended during execution of the called subprogram Control always returns to the caller when the called subprogram’s execution terminates 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 of a subprogram is the number, order, and types of its parameters 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
  • 2. ICS 313 - Fundamentals of Programming Languages 2 9.2 Fundamentals of Subprograms (continued) 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 Actual/Formal Parameter Correspondence Positional Keyword e.g. SORT(LIST => A, LENGTH => N); Advantage: order is irrelevant Disadvantage: user must know the formal parameter’s names Default Values: e.g. procedure SORT(LIST : LIST_TYPE; LENGTH : INTEGER := 100); ... SORT(LIST => A); Procedures provide user-defined statements Functions provide user-defined operators 9.3 Design Issues for Subprograms What parameter passing methods are provided? Are parameter types checked? Are local variables static or dynamic? What is the referencing environment of a passed subprogram? Are parameter types in passed subprograms checked? Can subprogram definitions be nested? Can subprograms be overloaded? Are subprograms allowed to be generic? Is separate or independent compilation supported?
  • 3. ICS 313 - Fundamentals of Programming Languages 3 9.4 Local referencing environments If local variables are stack-dynamic: Advantages Support for recursion Storage for locals is shared among some subprograms Disadvantages Allocation/deallocation time Indirect addressing Subprograms cannot be history sensitive Static locals are the opposite Language Examples FORTRAN 77 and 90 - most are static, but the implementor can choose either (User can force static with SAVE) C - both (variables declared to be static are) (default is stack dynamic) Pascal, Java, and Ada - dynamic only 9.5 Parameter Passing Methods We discuss these at several different levels Semantic Models: in mode, out mode, inout mode Conceptual Models of Transfer Physically move a value Move an access path
  • 4. ICS 313 - Fundamentals of Programming Languages 4 9.5 Parameter Passing Methods (continued) Implementation Models Pass-by-value (in mode) Either by physical move or access path 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) 9.5 Parameter Passing Methods (continued) Pass-by-result (out mode) Local’s value is passed back to the caller Physical move is usually used Disadvantages: If value is passed, time and space In both cases, order dependence may be a problem e.g. procedure sub1(y: int, z: int); ... sub1(x, x); Value of x in the caller depends on order of assignments at the return Pass-by-value-result (inout mode) Physical move, both ways Also called pass-by-copy Disadvantages: Those of pass-by-result Those of pass-by-value
  • 5. ICS 313 - Fundamentals of Programming Languages 5 9.5 Parameter Passing Methods (continued) 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 Allows aliasing Actual parameter collisions e.g. procedure sub1(a: int, b: int); ... sub1(x, x); Array element collisions e.g. sub1(a[i], a[j]); /* if i = j */ Also, sub2(a, a[i]); (a different one) Collision between formals and globals – 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!) 9.5 Parameter Passing Methods (continued) Pass-by-name (multiple 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 Purpose: flexibility of late binding 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]);
  • 6. ICS 313 - Fundamentals of Programming Languages 6 9.5 Parameter Passing Methods (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); Disadvantages of pass by name Very inefficient references Too tricky; hard to read and understand 9.5 Parameter Passing Methods (continued) Language Examples FORTRAN Before 77, pass-by-reference 77 - scalar variables are often passed by value-result ALGOL 60 Pass-by-name is default; pass-by-value is optional ALGOL W Pass-by-value-result C Pass-by-value Pascal and Modula-2 Default is pass-by-value; pass-by-reference is optional C++ Like C, but also allows reference type parameters, which provide the efficiency of pass-by-reference with in-mode semantics
  • 7. ICS 313 - Fundamentals of Programming Languages 7 9.5 Parameter Passing Methods (continued) Ada All three semantic modes are available If out, it cannot be referenced If in, it cannot be assigned Java Like C++, except only references Type checking parameters (Now considered very important for reliability) FORTRAN 77 and original C: none Pascal, FORTRAN 90, Java, and Ada: it is always required ANSI C and C++: choice is made by the user 9.5 Parameter Passing Methods (continued) 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 - same Reference - regardless of form, put the address in the stack 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
  • 8. ICS 313 - Fundamentals of Programming Languages 8 9.5 Parameter Passing Methods (continued) One possible stack implementation of the common parameter-passing methods 9.5 Parameter Passing Methods (continued) 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”
  • 9. ICS 313 - Fundamentals of Programming Languages 9 9.5 Parameter Passing Methods (continued) 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 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 (See example, p. 371) Pascal Not a problem (declared size is part of the array’s type) Ada Constrained arrays - like Pascal Unconstrained arrays - declared size is part of the object declaration (See example p. 371) (Java is similar) 9.5 Parameter Passing Methods (continued) Pre-90 FORTRAN Formal parameter declarations for arrays can include passed parameters e.g. SUBPROGRAM SUB(MATRIX, ROWS, COLS, RESULT) INTEGER ROWS, COLS REAL MATRIX (ROWS, COLS), RESULT ... END 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
  • 10. ICS 313 - Fundamentals of Programming Languages 10 9.6 Parameters that are Subprogram Names 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? 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) 9.6 Parameters that are Subprogram Names 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
  • 11. ICS 313 - Fundamentals of Programming Languages 11 9.7 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 9.8 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 Ada Types, subscript ranges, constant values, etc., can be generic in Ada subprograms and packages e.g. - see next page
  • 12. ICS 313 - Fundamentals of Programming Languages 12 9.8 Generic Subprograms (continued) generic type ELEMENT is private; type VECTOR is array (INTEGER range <>) of ELEMENT; procedure GENERIC_SORT(LIST: in out VECTOR); 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; procedure INTEGER_SORT is new GENERIC_SORT(ELEMENT => INTEGER; VECTOR => INT_ARRAY); 9.8 Generic Subprograms (continued) 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); 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);
  • 13. ICS 313 - Fundamentals of Programming Languages 13 9.8 Generic Subprograms (continued) C++ Templated functions e.g. template <class Type> Type max(Type first, Type second) { return first > second ? first : second; } C++ template functions are instantiated implicitly when the function is named in a call or when its address is taken with the & operator 9.8 Generic Subprograms (continued) Another example: 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 for (bottom = ... } //** end of generic_sort Example use: float flt_list[100]; ... generic_sort(flt_list, 100); // Implicit // instantiation
  • 14. ICS 313 - Fundamentals of Programming Languages 14 9.9 Separate & Independent Compilation 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 Separate compilation is compilation of some of the units of a program separately from the rest of the program, using interface nformation to check the correctness of the interface between the two parts Language Examples: FORTRAN II to FORTRAN 77 - independent FORTRAN 90, Ada, C++, Java - separate Pascal - allows neither 9.10 Design Issues for Functions Are side effects allowed? Two-way parameters (Ada does not allow) Nonlocal reference (all allow) What types of return values are allowed? Language Examples (for possible return types): FORTRAN, Pascal - only simple types C - any type except functions and arrays Ada - any type (but subprograms are not types) C++ and Java - like C, but also allow classes to be returned
  • 15. ICS 313 - Fundamentals of Programming Languages 15 9.11 Accessing Nonlocal Environments The nonlocal variables of a subprogram are those that are visible but not declared in the subprogram Global variables are those that may be visible in all of the subprograms of a program Methods: 1. FORTRAN COMMON The only way in pre-90 FORTRANs to access nonlocal variables Can be used to share data or share storage 9.11 Accessing Nonlocal Environments (continued) 2. Static scoping - discussed in Chapter 5 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) 4. External modules - Ada More about these later (Chapter 11) 5. Dynamic Scope - discussed in Chapter 5
  • 16. ICS 313 - Fundamentals of Programming Languages 16 9.12 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) 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? 9.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 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
  • 17. ICS 313 - Fundamentals of Programming Languages 17 9.13 Coroutines (continued) Examples