SlideShare a Scribd company logo
1 of 43
Download to read offline
Chapter 8: Subprograms 
Principles of Programming Languages
Contents 
•Fundamentals of Subprograms 
•Parameter-Passing Methods 
•Overloaded Subprograms 
•Generic Subprograms 
•Functions 
•User-Defined Overloaded Operators 
•Coroutines
Introduction 
•Two fundamental abstraction facilities 
–Process abstraction 
•Reuse a collection of statements 
•Abstracting the details of a computation by calling subprogram’s name 
–Data abstraction 
•How about methods of object-oriented languages?
General Characteristics 
•Each subprogram has a single entry point 
•There is only one subprogram in execution at any given time 
•Control always returns to the caller when the called subprogram’s execution terminates 
Subprogram A 
begin 
. . . . 
Call B 
. . . . 
end 
Subprogram B 
begin 
. . . . 
end
Basic Definitions 
•Subprogram definition 
•Subprogram call 
•Subprogram header 
Subprogram A 
begin 
. . . . 
Call B 
. . . . 
end 
Subprogram B begin . . . . end
Header Examples 
Subroutine Adder(parameters) Fortran 
procedure Adder(parameters) Ada 
def adder(parameters)= Scala 
void adder(parameters) C 
•Specify a kind of subprogram 
•Subprogram name 
•Optionally a list of parameters
Special Case: C/C++ 
•Parameter profile 
•Protocol 
•A subprogram declaration provides the protocol, but not the body, of the subprogram 
•Function declarations in C and C++ are often called prototypes 
•Reason: not allow forward references to subprogram
•Formal parameters vs. actual parameters 
•Positional (all proglang) 
–The binding of actual parameters to formal parameters is by position: the first actual parameter is bound to the first formal parameter and so forth 
–Safe and effective 
•Keyword (Python, Ada, Fortran 95, Python) 
–The name of the formal parameter to which an actual parameter is to be bound is specified with the actual parameter 
–Parameters can appear in any order 
Parameters
Parameters 
•In certain languages, formal parameters can have default values 
Python: 
def compute_pay(income, exemptions = 1, tax_rate) 
pay = compute_pay(20000.0, tax_rate = 0.15) 
C++: 
float compute_pay(float income, float tax_rate, 
int exemptions = 1) 
•C#: accept a variable number of parameters as long as they are of the same type 
public void Display(params int[] list)
Procedures and Functions 
•Procedures are collection of statements 
–Produce results by changing non-local variables or formal parameters that allow the transfer of data to the caller 
•Functions structurally resemble procedures but are semantically modeled on mathematical functions 
–They are expected to return a value and produce no side effects
Design Issues for Subprograms 
•Are local variables static or dynamic? 
•Can subprogram definitions appear in other subprogram definitions? 
•What parameter-passing methods are used? 
•Are parameter types checked? 
•Can subprograms be overloaded? 
•Can subprogram be generic?
Local Variables 
•Stack-dynamic 
–Where does the name come from? 
–Advantages 
•Support for recursion 
•Storage is shared among some subprograms 
–Disadvantages 
•Cost of allocation/de-allocation, initialization 
•Indirect addressing 
•Subprograms cannot be history sensitive 
–Default in most contemporary languages
Local Variables 
•Local variables can be static 
–Storage? 
–Advantages 
•Slightly more efficient: no indirection, no run-time overhead 
•Allow subprograms to be history-sensitive 
–Disadvantages: 
•Cannot support recursion 
•Storage cannot be shared 
–Supported in C/C++, Fortran 95
Nested Subprograms 
•Originating from Algol 60: Algol 68, Pascal, Ada. Recently, JavaScript, Python, and Ruby 
•Hierarchy of both logic and scopes 
•Usually with static scoping: grant access to nonlocal variables in enclosing subprograms 
•Problems: Chapter 5 
•Examples: many in your Tutorial on Scopes with Ada
Parameter-Passing Methods 
•Ways in which parameters are transmitted to and/or from called subprograms 
•Semantics models: formal parameters can 
–Receive data from actual parameters: in mode 
–Transmit data to actual parameters: out mode 
–Do both: inout mode 
•Data transfer models: 
–Actual value is copied 
–Access path is transmitted
7 
Pass-by-Value (In Mode) 
•Normally implemented by copying, or 
•Transmitting an access path but have to enforce write protection 
•Advantage: fast for scalars 
•Disadvantages: 
–When copies are used, additional storage is required 
–Storage and copy operations can be costly 
5 
5 
Caller 
Callee 
Call 
a 
x 
Return
Pass-by-Result (Out Mode) 
•Potential problem: 
void Fixer(out int x, out int y) { C# 
x = 17; y = 35; 
} 
f.Fixer(out a, out a); 
void DoIt(out int x, out int index) { C# 
x = 17; index = 42; 
} 
sub = 21; 
f.DoIt(out list[sub], out sub) 
5 
7 
Caller 
Callee 
Call 
a 
x 
Return 
7
Pass-by-Value-Result (Inout Mode) 
•A combination of pass-by-value and pass-by- result 
•Sometimes called pass-by-copy 
•Formal parameters have local storage 
•Disadvantages: 
–Those of pass-by-result 
–Those of pass-by-value 
5 
7 
Caller 
Callee 
Call 
a 
x 
Return 
7 
5
Pass-by-Reference (Inout Mode) 
•Pass an access path, usually just an address 
•Passing process is efficient (no copying and no duplicated storage) 
•Disadvantages 
–Slower accesses (compared to pass-by-value) to formal parameters 
–Potentials for un-wanted side effects 
–Un-wanted aliases (access broadened) 
5 
Caller 
Callee 
a 
x 
7 
Reference
Pass-by-Name (Inout Mode) 
•By textual substitution 
•Actual binding to a value or address takes place at the time of a reference or assignment
type VECT = array [1..3] of integer; 
procedure SUB2 (name I, J: integer); 
begin 
I := I + 1; 
J := J + 1; 
write(I, J) 
end; 
procedure SUB1; 
var A: VECT; 
K: integer; 
begin 
A[1] := 7; A[2] := 8; A[3] := 9; 
K := 2; 
SUB2(K, A[K]); 
for K := 1 to 3 do write(A[K]) 
end; 
K := K + 1; 
A[K] := A[K] + 1; 
write(K,A[K]) 
Pass-by-Name (Inout mode)
•Parameter communication often takes place through the run-time stack 
Implementing Parameter-Passing Methods
Parameter-Passing Methods in Common Language 
•C 
–Default: pass-by-value 
–Pass-by-reference is achieved by using pointers as parameters 
•C++ 
–Using reference type for pass-by-reference 
–How about constant reference? 
•Java 
–All parameters are passed by value 
–Objects copy its reference
Parameter-Passing Methods in Common Language 
•Ada 
–Three semantics modes of parameter transmission: in, out, in out; in is the default mode 
•C# 
–Default method: pass-by-value 
–Pass-by-reference: ref 
–Out mode: out
Type Checking Parameters 
•Considered very important for reliability 
•Original C: no type checking 
•C++: yes, but can pass by using ellipsis. For example, printf function 
•C#: coercions in pass-by-value, no coercions in pass-by-reference 
•Python, Ruby: formal parameters are typeless, no type checking is needed
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/C++: 
–must declare the matrix size in parameters 
–macro is a good choice 
•Java, C#: every matrix has length function
•Two important considerations 
–Efficiency 
–One-way or two-way data transfer is needed 
•But the above considerations are in conflict 
–Good programming suggest limited access to variables, which means one-way whenever possible 
–But pass-by-reference is more efficient to pass structures of significant size 
Design Considerations
Parameters That Are Subprograms 
•It is sometimes convenient to pass subprogram names as parameters 
•Issues: 
–Are parameter of transferring subprogram type- checked? 
–In languages that allow nested subprogram, what referencing environment for executing the passed subprogram should be used?
Parameters as Subprograms: Type Checking 
•Are parameter of transferring subprogram type-checked? 
•C and C++: functions cannot be passed as parameters but pointers to functions can be passed; parameters can be type checked 
•Ada does not allow subprogram parameters; a similar alternative is provided via Ada’s generic facility
Parameters as Subprograms: Referencing Environment 
•What referencing environment for executing the passed subprogram should be used? 
•Shallow binding: The environment of the call statement that enacts the passed subprogram 
•Deep binding: The environment of the definition of the passed subprogram 
•Ad hoc binding: The environment of the call statement that passed the subprogram
Parameters as Subprograms: Referencing Environment 
function sub1() { 
var x; 
function sub2() { 
alert(x); 
}; 
function sub3() { 
var x; 
x = 3; 
sub4(sub2); 
}; 
function sub4(subx) { 
var x; 
x = 4; 
subx(); 
}; 
x = 1; 
sub3(); 
} 
•Shallow binding: 
4 
•Deep binding: 
1 
•Ad hoc binding: 
3
Overloaded Subprograms 
•An overloaded subprogram is one that has the same name as another subprogram in the same referencing environment 
–Every version of an overloaded subprogram has a unique protocol (number, order, types of params and return type) 
•C++, Java, C#, and Ada include predefined overloaded subprograms 
•In Ada, the return type of an overloaded function can be used to disambiguate calls (thus two overloaded functions can have the same parameters)
Generic Subprograms 
•A polymorphic subprogram takes parameters of different types on different activations 
•Overloaded subprograms: ad hoc polymorphism 
•Generic subprograms: parametric polymorphism 
•Ada, C++, Java 5.0, C# 2005 (Scala)
Examples of parametric polymorphism: C++ 
template <class Type> 
Type max(Type first, Type second) { 
return first > second ? first : second; 
} 
•The above template can be instantiated for any type for which operator > is defined 
int max (int first, int second) { 
return first > second? first : second; 
}
Design Issues for Functions 
•Are side effects allowed? 
–Parameters should always be in-mode to reduce side effect (like Ada) 
•What types of return values are allowed? 
–Most imperative languages restrict the return types 
–C allows any type except arrays and functions 
–C++ is like C but also allows user-defined types 
–Python, Ruby: functions are first class object 
–Java and C# do not have functions but methods can return any type, except method (not a type)
Design Issues for Functions 
•Number of returned values? 
–In most languages, only a single value can be returned from a function 
–Ruby: return an array of value if there are more than one expression
User-Defined Overloaded Operators 
•Operators can be overloaded in Ada, C++, Python and Ruby 
•Data Structures and Algorithms 
int operator *(const vector &a, const vector &b, int len);
•A coroutine is a subprogram that has multiple entries and controls them itself 
•A coroutine call is named a resume 
sub co1() { 
. . . 
resume co2(); 
. . . 
resume co3(); 
. . . 
} 
Coroutines
1-39 
Coroutines Illustrated: Possible Execution Controls
Coroutines Illustrated: Possible Execution Controls
Coroutines 
•Coroutines repeatedly resume each other 
•Coroutines provide quasi-concurrent execution of program units (the coroutines); their execution is interleaved, but not overlapped 
•Coroutines are created by a program unit called the master unit
Coroutines Illustrated 
•Simulation of a card game 
•Four players will have four coroutines, each with collection, or hand, of cards 
•Master program then start by resuming one of the player coroutines 
•After this player played its turn, could resume the next player coroutine and so forth
•A subprogram definition describes the actions represented by the subprogram 
•Subprograms can be either functions or procedures 
•Local variables in subprograms can be stack- dynamic or static 
•Three models of parameter passing: in mode, out mode, and inout mode 
•Some languages allow operator overloading 
•Subprograms can be generic 
•A coroutine is a special subprogram with multiple entries 
Summary

More Related Content

What's hot

Asymptotic notations
Asymptotic notationsAsymptotic notations
Asymptotic notationsNikhil Sharma
 
Compiler design syntax analysis
Compiler design syntax analysisCompiler design syntax analysis
Compiler design syntax analysisRicha Sharma
 
02. chapter 3 lexical analysis
02. chapter 3   lexical analysis02. chapter 3   lexical analysis
02. chapter 3 lexical analysisraosir123
 
A Role of Lexical Analyzer
A Role of Lexical AnalyzerA Role of Lexical Analyzer
A Role of Lexical AnalyzerArchana Gopinath
 
standard template library(STL) in C++
standard template library(STL) in C++standard template library(STL) in C++
standard template library(STL) in C++•sreejith •sree
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT03062679929
 
Algorithm and pseudocode conventions
Algorithm and pseudocode conventionsAlgorithm and pseudocode conventions
Algorithm and pseudocode conventionssaranyatdr
 
Symbol table in compiler Design
Symbol table in compiler DesignSymbol table in compiler Design
Symbol table in compiler DesignKuppusamy P
 
Lecture 12 intermediate code generation
Lecture 12 intermediate code generationLecture 12 intermediate code generation
Lecture 12 intermediate code generationIffat Anjum
 
Analysis of algorithms
Analysis of algorithmsAnalysis of algorithms
Analysis of algorithmsGanesh Solanke
 
Code optimization in compiler design
Code optimization in compiler designCode optimization in compiler design
Code optimization in compiler designKuppusamy P
 
Time and space complexity
Time and space complexityTime and space complexity
Time and space complexityAnkit Katiyar
 
Code generation in Compiler Design
Code generation in Compiler DesignCode generation in Compiler Design
Code generation in Compiler DesignKuppusamy P
 

What's hot (20)

Asymptotic notations
Asymptotic notationsAsymptotic notations
Asymptotic notations
 
Recursion in c++
Recursion in c++Recursion in c++
Recursion in c++
 
Compiler design syntax analysis
Compiler design syntax analysisCompiler design syntax analysis
Compiler design syntax analysis
 
02. chapter 3 lexical analysis
02. chapter 3   lexical analysis02. chapter 3   lexical analysis
02. chapter 3 lexical analysis
 
Introduction to Compiler design
Introduction to Compiler design Introduction to Compiler design
Introduction to Compiler design
 
Syntax analysis
Syntax analysisSyntax analysis
Syntax analysis
 
Run time storage
Run time storageRun time storage
Run time storage
 
Phases of compiler
Phases of compilerPhases of compiler
Phases of compiler
 
A Role of Lexical Analyzer
A Role of Lexical AnalyzerA Role of Lexical Analyzer
A Role of Lexical Analyzer
 
standard template library(STL) in C++
standard template library(STL) in C++standard template library(STL) in C++
standard template library(STL) in C++
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
 
Algorithm and pseudocode conventions
Algorithm and pseudocode conventionsAlgorithm and pseudocode conventions
Algorithm and pseudocode conventions
 
Symbol table in compiler Design
Symbol table in compiler DesignSymbol table in compiler Design
Symbol table in compiler Design
 
Lecture 12 intermediate code generation
Lecture 12 intermediate code generationLecture 12 intermediate code generation
Lecture 12 intermediate code generation
 
Analysis of algorithms
Analysis of algorithmsAnalysis of algorithms
Analysis of algorithms
 
Code optimization in compiler design
Code optimization in compiler designCode optimization in compiler design
Code optimization in compiler design
 
Time and space complexity
Time and space complexityTime and space complexity
Time and space complexity
 
Code Optimization
Code OptimizationCode Optimization
Code Optimization
 
Code generation in Compiler Design
Code generation in Compiler DesignCode generation in Compiler Design
Code generation in Compiler Design
 
Scheduling algorithms
Scheduling algorithmsScheduling algorithms
Scheduling algorithms
 

Viewers also liked

Object Oriented Programming - Abstraction & Encapsulation
Object Oriented Programming - Abstraction & EncapsulationObject Oriented Programming - Abstraction & Encapsulation
Object Oriented Programming - Abstraction & EncapsulationDudy Ali
 
pointers,virtual functions and polymorphism
pointers,virtual functions and polymorphismpointers,virtual functions and polymorphism
pointers,virtual functions and polymorphismrattaj
 
Java multi threading
Java multi threadingJava multi threading
Java multi threadingRaja Sekhar
 
Presentation on generation of languages
Presentation on generation of languagesPresentation on generation of languages
Presentation on generation of languagesRicha Pant
 
Unit1 principle of programming language
Unit1 principle of programming languageUnit1 principle of programming language
Unit1 principle of programming languageVasavi College of Engg
 
Pointers, virtual function and polymorphism
Pointers, virtual function and polymorphismPointers, virtual function and polymorphism
Pointers, virtual function and polymorphismlalithambiga kamaraj
 
Unit 3 principles of programming language
Unit 3 principles of programming languageUnit 3 principles of programming language
Unit 3 principles of programming languageVasavi College of Engg
 

Viewers also liked (10)

Object Oriented Programming - Abstraction & Encapsulation
Object Oriented Programming - Abstraction & EncapsulationObject Oriented Programming - Abstraction & Encapsulation
Object Oriented Programming - Abstraction & Encapsulation
 
9 subprograms
9 subprograms9 subprograms
9 subprograms
 
pointers,virtual functions and polymorphism
pointers,virtual functions and polymorphismpointers,virtual functions and polymorphism
pointers,virtual functions and polymorphism
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
 
Presentation on generation of languages
Presentation on generation of languagesPresentation on generation of languages
Presentation on generation of languages
 
Unit1 principle of programming language
Unit1 principle of programming languageUnit1 principle of programming language
Unit1 principle of programming language
 
07. Virtual Functions
07. Virtual Functions07. Virtual Functions
07. Virtual Functions
 
Pointers, virtual function and polymorphism
Pointers, virtual function and polymorphismPointers, virtual function and polymorphism
Pointers, virtual function and polymorphism
 
Unit 3 principles of programming language
Unit 3 principles of programming languageUnit 3 principles of programming language
Unit 3 principles of programming language
 

Similar to Chapter 8 Principles of Programming Languages Subprograms

Similar to Chapter 8 Principles of Programming Languages Subprograms (20)

Plc part 3
Plc  part 3Plc  part 3
Plc part 3
 
10 implementing subprograms
10 implementing subprograms10 implementing subprograms
10 implementing subprograms
 
Subprogramms
SubprogrammsSubprogramms
Subprogramms
 
Lec16-CS110 Computational Engineering
Lec16-CS110 Computational EngineeringLec16-CS110 Computational Engineering
Lec16-CS110 Computational Engineering
 
Improved Developer Productivity In JDK8
Improved Developer Productivity In JDK8Improved Developer Productivity In JDK8
Improved Developer Productivity In JDK8
 
Functions
FunctionsFunctions
Functions
 
Unit 2
Unit 2Unit 2
Unit 2
 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project Lambda
 
Compiler Construction
Compiler ConstructionCompiler Construction
Compiler Construction
 
9 subprograms
9 subprograms9 subprograms
9 subprograms
 
Subprogram
SubprogramSubprogram
Subprogram
 
Functions
FunctionsFunctions
Functions
 
Monolithic and Procedural Programming
Monolithic and Procedural ProgrammingMonolithic and Procedural Programming
Monolithic and Procedural Programming
 
Lecture 15 run timeenvironment_2
Lecture 15 run timeenvironment_2Lecture 15 run timeenvironment_2
Lecture 15 run timeenvironment_2
 
21E-WhatsTheFuss_UsingProceduresAndServicePrograms.pdf
21E-WhatsTheFuss_UsingProceduresAndServicePrograms.pdf21E-WhatsTheFuss_UsingProceduresAndServicePrograms.pdf
21E-WhatsTheFuss_UsingProceduresAndServicePrograms.pdf
 
07 control+structures
07 control+structures07 control+structures
07 control+structures
 
Basics of cpp
Basics of cppBasics of cpp
Basics of cpp
 
c++ Unit I.pptx
c++ Unit I.pptxc++ Unit I.pptx
c++ Unit I.pptx
 
Functions
FunctionsFunctions
Functions
 
Unit 1
Unit  1Unit  1
Unit 1
 

More from baran19901990

Config websocket on apache
Config websocket on apacheConfig websocket on apache
Config websocket on apachebaran19901990
 
Nhập môn công tác kỹ sư
Nhập môn công tác kỹ sưNhập môn công tác kỹ sư
Nhập môn công tác kỹ sưbaran19901990
 
Tìm đường đi xe buýt trong TPHCM bằng Google Map
Tìm đường đi xe buýt trong TPHCM bằng Google MapTìm đường đi xe buýt trong TPHCM bằng Google Map
Tìm đường đi xe buýt trong TPHCM bằng Google Mapbaran19901990
 
How to build a news website use CMS wordpress
How to build a news website use CMS wordpressHow to build a news website use CMS wordpress
How to build a news website use CMS wordpressbaran19901990
 
How to install nginx vs unicorn
How to install nginx vs unicornHow to install nginx vs unicorn
How to install nginx vs unicornbaran19901990
 
Untitled Presentation
Untitled PresentationUntitled Presentation
Untitled Presentationbaran19901990
 
10 logic+programming+with+prolog
10 logic+programming+with+prolog10 logic+programming+with+prolog
10 logic+programming+with+prologbaran19901990
 
09 implementing+subprograms
09 implementing+subprograms09 implementing+subprograms
09 implementing+subprogramsbaran19901990
 
How to install git on ubuntu
How to install git on ubuntuHow to install git on ubuntu
How to install git on ubuntubaran19901990
 
Báo cáo mô hình quản lý khách sạn
Báo cáo mô hình quản lý khách sạnBáo cáo mô hình quản lý khách sạn
Báo cáo mô hình quản lý khách sạnbaran19901990
 

More from baran19901990 (20)

Config websocket on apache
Config websocket on apacheConfig websocket on apache
Config websocket on apache
 
Nhập môn công tác kỹ sư
Nhập môn công tác kỹ sưNhập môn công tác kỹ sư
Nhập môn công tác kỹ sư
 
Tìm đường đi xe buýt trong TPHCM bằng Google Map
Tìm đường đi xe buýt trong TPHCM bằng Google MapTìm đường đi xe buýt trong TPHCM bằng Google Map
Tìm đường đi xe buýt trong TPHCM bằng Google Map
 
How to build a news website use CMS wordpress
How to build a news website use CMS wordpressHow to build a news website use CMS wordpress
How to build a news website use CMS wordpress
 
How to install nginx vs unicorn
How to install nginx vs unicornHow to install nginx vs unicorn
How to install nginx vs unicorn
 
Untitled Presentation
Untitled PresentationUntitled Presentation
Untitled Presentation
 
Control structure
Control structureControl structure
Control structure
 
Lexical
LexicalLexical
Lexical
 
Introduction
IntroductionIntroduction
Introduction
 
Datatype
DatatypeDatatype
Datatype
 
10 logic+programming+with+prolog
10 logic+programming+with+prolog10 logic+programming+with+prolog
10 logic+programming+with+prolog
 
09 implementing+subprograms
09 implementing+subprograms09 implementing+subprograms
09 implementing+subprograms
 
How to install git on ubuntu
How to install git on ubuntuHow to install git on ubuntu
How to install git on ubuntu
 
Ruby notification
Ruby notificationRuby notification
Ruby notification
 
Rails notification
Rails notificationRails notification
Rails notification
 
Linux notification
Linux notificationLinux notification
Linux notification
 
Lab4
Lab4Lab4
Lab4
 
Lab5
Lab5Lab5
Lab5
 
09
0909
09
 
Báo cáo mô hình quản lý khách sạn
Báo cáo mô hình quản lý khách sạnBáo cáo mô hình quản lý khách sạn
Báo cáo mô hình quản lý khách sạn
 

Recently uploaded

PHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 DocumentationPHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 DocumentationLinaWolf1
 
Q4-1-Illustrating-Hypothesis-Testing.pptx
Q4-1-Illustrating-Hypothesis-Testing.pptxQ4-1-Illustrating-Hypothesis-Testing.pptx
Q4-1-Illustrating-Hypothesis-Testing.pptxeditsforyah
 
SCM Symposium PPT Format Customer loyalty is predi
SCM Symposium PPT Format Customer loyalty is prediSCM Symposium PPT Format Customer loyalty is predi
SCM Symposium PPT Format Customer loyalty is predieusebiomeyer
 
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书rnrncn29
 
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一Fs
 
Top 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptxTop 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptxDyna Gilbert
 
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一Fs
 
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作ys8omjxb
 
Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170Sonam Pathan
 
Film cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasaFilm cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasa494f574xmv
 
Magic exist by Marta Loveguard - presentation.pptx
Magic exist by Marta Loveguard - presentation.pptxMagic exist by Marta Loveguard - presentation.pptx
Magic exist by Marta Loveguard - presentation.pptxMartaLoveguard
 
Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24Paul Calvano
 
Contact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New DelhiContact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New Delhimiss dipika
 
Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...Excelmac1
 
Elevate Your Business with Our IT Expertise in New Orleans
Elevate Your Business with Our IT Expertise in New OrleansElevate Your Business with Our IT Expertise in New Orleans
Elevate Your Business with Our IT Expertise in New Orleanscorenetworkseo
 
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一Fs
 
NSX-T and Service Interfaces presentation
NSX-T and Service Interfaces presentationNSX-T and Service Interfaces presentation
NSX-T and Service Interfaces presentationMarko4394
 
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一z xss
 

Recently uploaded (20)

PHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 DocumentationPHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 Documentation
 
Q4-1-Illustrating-Hypothesis-Testing.pptx
Q4-1-Illustrating-Hypothesis-Testing.pptxQ4-1-Illustrating-Hypothesis-Testing.pptx
Q4-1-Illustrating-Hypothesis-Testing.pptx
 
SCM Symposium PPT Format Customer loyalty is predi
SCM Symposium PPT Format Customer loyalty is prediSCM Symposium PPT Format Customer loyalty is predi
SCM Symposium PPT Format Customer loyalty is predi
 
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
 
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
 
Top 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptxTop 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptx
 
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
 
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
 
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
 
Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170
 
Film cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasaFilm cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasa
 
Magic exist by Marta Loveguard - presentation.pptx
Magic exist by Marta Loveguard - presentation.pptxMagic exist by Marta Loveguard - presentation.pptx
Magic exist by Marta Loveguard - presentation.pptx
 
Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24
 
Hot Sexy call girls in Rk Puram 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in  Rk Puram 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in  Rk Puram 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Rk Puram 🔝 9953056974 🔝 Delhi escort Service
 
Contact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New DelhiContact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New Delhi
 
Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...
 
Elevate Your Business with Our IT Expertise in New Orleans
Elevate Your Business with Our IT Expertise in New OrleansElevate Your Business with Our IT Expertise in New Orleans
Elevate Your Business with Our IT Expertise in New Orleans
 
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
 
NSX-T and Service Interfaces presentation
NSX-T and Service Interfaces presentationNSX-T and Service Interfaces presentation
NSX-T and Service Interfaces presentation
 
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
 

Chapter 8 Principles of Programming Languages Subprograms

  • 1. Chapter 8: Subprograms Principles of Programming Languages
  • 2. Contents •Fundamentals of Subprograms •Parameter-Passing Methods •Overloaded Subprograms •Generic Subprograms •Functions •User-Defined Overloaded Operators •Coroutines
  • 3. Introduction •Two fundamental abstraction facilities –Process abstraction •Reuse a collection of statements •Abstracting the details of a computation by calling subprogram’s name –Data abstraction •How about methods of object-oriented languages?
  • 4. General Characteristics •Each subprogram has a single entry point •There is only one subprogram in execution at any given time •Control always returns to the caller when the called subprogram’s execution terminates Subprogram A begin . . . . Call B . . . . end Subprogram B begin . . . . end
  • 5. Basic Definitions •Subprogram definition •Subprogram call •Subprogram header Subprogram A begin . . . . Call B . . . . end Subprogram B begin . . . . end
  • 6. Header Examples Subroutine Adder(parameters) Fortran procedure Adder(parameters) Ada def adder(parameters)= Scala void adder(parameters) C •Specify a kind of subprogram •Subprogram name •Optionally a list of parameters
  • 7. Special Case: C/C++ •Parameter profile •Protocol •A subprogram declaration provides the protocol, but not the body, of the subprogram •Function declarations in C and C++ are often called prototypes •Reason: not allow forward references to subprogram
  • 8. •Formal parameters vs. actual parameters •Positional (all proglang) –The binding of actual parameters to formal parameters is by position: the first actual parameter is bound to the first formal parameter and so forth –Safe and effective •Keyword (Python, Ada, Fortran 95, Python) –The name of the formal parameter to which an actual parameter is to be bound is specified with the actual parameter –Parameters can appear in any order Parameters
  • 9. Parameters •In certain languages, formal parameters can have default values Python: def compute_pay(income, exemptions = 1, tax_rate) pay = compute_pay(20000.0, tax_rate = 0.15) C++: float compute_pay(float income, float tax_rate, int exemptions = 1) •C#: accept a variable number of parameters as long as they are of the same type public void Display(params int[] list)
  • 10. Procedures and Functions •Procedures are collection of statements –Produce results by changing non-local variables or formal parameters that allow the transfer of data to the caller •Functions structurally resemble procedures but are semantically modeled on mathematical functions –They are expected to return a value and produce no side effects
  • 11. Design Issues for Subprograms •Are local variables static or dynamic? •Can subprogram definitions appear in other subprogram definitions? •What parameter-passing methods are used? •Are parameter types checked? •Can subprograms be overloaded? •Can subprogram be generic?
  • 12. Local Variables •Stack-dynamic –Where does the name come from? –Advantages •Support for recursion •Storage is shared among some subprograms –Disadvantages •Cost of allocation/de-allocation, initialization •Indirect addressing •Subprograms cannot be history sensitive –Default in most contemporary languages
  • 13. Local Variables •Local variables can be static –Storage? –Advantages •Slightly more efficient: no indirection, no run-time overhead •Allow subprograms to be history-sensitive –Disadvantages: •Cannot support recursion •Storage cannot be shared –Supported in C/C++, Fortran 95
  • 14. Nested Subprograms •Originating from Algol 60: Algol 68, Pascal, Ada. Recently, JavaScript, Python, and Ruby •Hierarchy of both logic and scopes •Usually with static scoping: grant access to nonlocal variables in enclosing subprograms •Problems: Chapter 5 •Examples: many in your Tutorial on Scopes with Ada
  • 15. Parameter-Passing Methods •Ways in which parameters are transmitted to and/or from called subprograms •Semantics models: formal parameters can –Receive data from actual parameters: in mode –Transmit data to actual parameters: out mode –Do both: inout mode •Data transfer models: –Actual value is copied –Access path is transmitted
  • 16. 7 Pass-by-Value (In Mode) •Normally implemented by copying, or •Transmitting an access path but have to enforce write protection •Advantage: fast for scalars •Disadvantages: –When copies are used, additional storage is required –Storage and copy operations can be costly 5 5 Caller Callee Call a x Return
  • 17. Pass-by-Result (Out Mode) •Potential problem: void Fixer(out int x, out int y) { C# x = 17; y = 35; } f.Fixer(out a, out a); void DoIt(out int x, out int index) { C# x = 17; index = 42; } sub = 21; f.DoIt(out list[sub], out sub) 5 7 Caller Callee Call a x Return 7
  • 18. Pass-by-Value-Result (Inout Mode) •A combination of pass-by-value and pass-by- result •Sometimes called pass-by-copy •Formal parameters have local storage •Disadvantages: –Those of pass-by-result –Those of pass-by-value 5 7 Caller Callee Call a x Return 7 5
  • 19. Pass-by-Reference (Inout Mode) •Pass an access path, usually just an address •Passing process is efficient (no copying and no duplicated storage) •Disadvantages –Slower accesses (compared to pass-by-value) to formal parameters –Potentials for un-wanted side effects –Un-wanted aliases (access broadened) 5 Caller Callee a x 7 Reference
  • 20. Pass-by-Name (Inout Mode) •By textual substitution •Actual binding to a value or address takes place at the time of a reference or assignment
  • 21. type VECT = array [1..3] of integer; procedure SUB2 (name I, J: integer); begin I := I + 1; J := J + 1; write(I, J) end; procedure SUB1; var A: VECT; K: integer; begin A[1] := 7; A[2] := 8; A[3] := 9; K := 2; SUB2(K, A[K]); for K := 1 to 3 do write(A[K]) end; K := K + 1; A[K] := A[K] + 1; write(K,A[K]) Pass-by-Name (Inout mode)
  • 22. •Parameter communication often takes place through the run-time stack Implementing Parameter-Passing Methods
  • 23. Parameter-Passing Methods in Common Language •C –Default: pass-by-value –Pass-by-reference is achieved by using pointers as parameters •C++ –Using reference type for pass-by-reference –How about constant reference? •Java –All parameters are passed by value –Objects copy its reference
  • 24. Parameter-Passing Methods in Common Language •Ada –Three semantics modes of parameter transmission: in, out, in out; in is the default mode •C# –Default method: pass-by-value –Pass-by-reference: ref –Out mode: out
  • 25. Type Checking Parameters •Considered very important for reliability •Original C: no type checking •C++: yes, but can pass by using ellipsis. For example, printf function •C#: coercions in pass-by-value, no coercions in pass-by-reference •Python, Ruby: formal parameters are typeless, no type checking is needed
  • 26. 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/C++: –must declare the matrix size in parameters –macro is a good choice •Java, C#: every matrix has length function
  • 27. •Two important considerations –Efficiency –One-way or two-way data transfer is needed •But the above considerations are in conflict –Good programming suggest limited access to variables, which means one-way whenever possible –But pass-by-reference is more efficient to pass structures of significant size Design Considerations
  • 28. Parameters That Are Subprograms •It is sometimes convenient to pass subprogram names as parameters •Issues: –Are parameter of transferring subprogram type- checked? –In languages that allow nested subprogram, what referencing environment for executing the passed subprogram should be used?
  • 29. Parameters as Subprograms: Type Checking •Are parameter of transferring subprogram type-checked? •C and C++: functions cannot be passed as parameters but pointers to functions can be passed; parameters can be type checked •Ada does not allow subprogram parameters; a similar alternative is provided via Ada’s generic facility
  • 30. Parameters as Subprograms: Referencing Environment •What referencing environment for executing the passed subprogram should be used? •Shallow binding: The environment of the call statement that enacts the passed subprogram •Deep binding: The environment of the definition of the passed subprogram •Ad hoc binding: The environment of the call statement that passed the subprogram
  • 31. Parameters as Subprograms: Referencing Environment function sub1() { var x; function sub2() { alert(x); }; function sub3() { var x; x = 3; sub4(sub2); }; function sub4(subx) { var x; x = 4; subx(); }; x = 1; sub3(); } •Shallow binding: 4 •Deep binding: 1 •Ad hoc binding: 3
  • 32. Overloaded Subprograms •An overloaded subprogram is one that has the same name as another subprogram in the same referencing environment –Every version of an overloaded subprogram has a unique protocol (number, order, types of params and return type) •C++, Java, C#, and Ada include predefined overloaded subprograms •In Ada, the return type of an overloaded function can be used to disambiguate calls (thus two overloaded functions can have the same parameters)
  • 33. Generic Subprograms •A polymorphic subprogram takes parameters of different types on different activations •Overloaded subprograms: ad hoc polymorphism •Generic subprograms: parametric polymorphism •Ada, C++, Java 5.0, C# 2005 (Scala)
  • 34. Examples of parametric polymorphism: C++ template <class Type> Type max(Type first, Type second) { return first > second ? first : second; } •The above template can be instantiated for any type for which operator > is defined int max (int first, int second) { return first > second? first : second; }
  • 35. Design Issues for Functions •Are side effects allowed? –Parameters should always be in-mode to reduce side effect (like Ada) •What types of return values are allowed? –Most imperative languages restrict the return types –C allows any type except arrays and functions –C++ is like C but also allows user-defined types –Python, Ruby: functions are first class object –Java and C# do not have functions but methods can return any type, except method (not a type)
  • 36. Design Issues for Functions •Number of returned values? –In most languages, only a single value can be returned from a function –Ruby: return an array of value if there are more than one expression
  • 37. User-Defined Overloaded Operators •Operators can be overloaded in Ada, C++, Python and Ruby •Data Structures and Algorithms int operator *(const vector &a, const vector &b, int len);
  • 38. •A coroutine is a subprogram that has multiple entries and controls them itself •A coroutine call is named a resume sub co1() { . . . resume co2(); . . . resume co3(); . . . } Coroutines
  • 39. 1-39 Coroutines Illustrated: Possible Execution Controls
  • 40. Coroutines Illustrated: Possible Execution Controls
  • 41. Coroutines •Coroutines repeatedly resume each other •Coroutines provide quasi-concurrent execution of program units (the coroutines); their execution is interleaved, but not overlapped •Coroutines are created by a program unit called the master unit
  • 42. Coroutines Illustrated •Simulation of a card game •Four players will have four coroutines, each with collection, or hand, of cards •Master program then start by resuming one of the player coroutines •After this player played its turn, could resume the next player coroutine and so forth
  • 43. •A subprogram definition describes the actions represented by the subprogram •Subprograms can be either functions or procedures •Local variables in subprograms can be stack- dynamic or static •Three models of parameter passing: in mode, out mode, and inout mode •Some languages allow operator overloading •Subprograms can be generic •A coroutine is a special subprogram with multiple entries Summary