SlideShare uma empresa Scribd logo
1 de 43
Baixar para ler 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

Mais conteúdo relacionado

Mais procurados

Symbol table in compiler Design
Symbol table in compiler DesignSymbol table in compiler Design
Symbol table in compiler DesignKuppusamy P
 
Unit 2 Principles of Programming Languages
Unit 2 Principles of Programming LanguagesUnit 2 Principles of Programming Languages
Unit 2 Principles of Programming LanguagesVasavi College of Engg
 
Type checking in compiler design
Type checking in compiler designType checking in compiler design
Type checking in compiler designSudip Singh
 
Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm KristinaBorooah
 
Object Oriented Analysis and Design
Object Oriented Analysis and DesignObject Oriented Analysis and Design
Object Oriented Analysis and DesignHaitham El-Ghareeb
 
Code generator
Code generatorCode generator
Code generatorTech_MX
 
Storage classes in c++
Storage classes in c++Storage classes in c++
Storage classes in c++Jaspal Singh
 
Intermediate code generation in Compiler Design
Intermediate code generation in Compiler DesignIntermediate code generation in Compiler Design
Intermediate code generation in Compiler DesignKuppusamy P
 
Finite Automata in compiler design
Finite Automata in compiler designFinite Automata in compiler design
Finite Automata in compiler designRiazul Islam
 
Symbol table design (Compiler Construction)
Symbol table design (Compiler Construction)Symbol table design (Compiler Construction)
Symbol table design (Compiler Construction)Tech_MX
 
Bottom - Up Parsing
Bottom - Up ParsingBottom - Up Parsing
Bottom - Up Parsingkunj desai
 
Chapter 1 1
Chapter 1 1Chapter 1 1
Chapter 1 1bolovv
 
Object Modeling Techniques
Object Modeling TechniquesObject Modeling Techniques
Object Modeling TechniquesShilpa Wadhwani
 
System Programming- Unit I
System Programming- Unit ISystem Programming- Unit I
System Programming- Unit ISaranya1702
 

Mais procurados (20)

Symbol table in compiler Design
Symbol table in compiler DesignSymbol table in compiler Design
Symbol table in compiler Design
 
Unit 2 Principles of Programming Languages
Unit 2 Principles of Programming LanguagesUnit 2 Principles of Programming Languages
Unit 2 Principles of Programming Languages
 
Specification-of-tokens
Specification-of-tokensSpecification-of-tokens
Specification-of-tokens
 
Type checking in compiler design
Type checking in compiler designType checking in compiler design
Type checking in compiler design
 
Arrays
ArraysArrays
Arrays
 
Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm
 
Pointer to function 1
Pointer to function 1Pointer to function 1
Pointer to function 1
 
Object Oriented Analysis and Design
Object Oriented Analysis and DesignObject Oriented Analysis and Design
Object Oriented Analysis and Design
 
Queue ppt
Queue pptQueue ppt
Queue ppt
 
Code generator
Code generatorCode generator
Code generator
 
Storage classes in c++
Storage classes in c++Storage classes in c++
Storage classes in c++
 
Intermediate code generation in Compiler Design
Intermediate code generation in Compiler DesignIntermediate code generation in Compiler Design
Intermediate code generation in Compiler Design
 
Finite Automata in compiler design
Finite Automata in compiler designFinite Automata in compiler design
Finite Automata in compiler design
 
Symbol table design (Compiler Construction)
Symbol table design (Compiler Construction)Symbol table design (Compiler Construction)
Symbol table design (Compiler Construction)
 
Bottom - Up Parsing
Bottom - Up ParsingBottom - Up Parsing
Bottom - Up Parsing
 
Chapter 1 1
Chapter 1 1Chapter 1 1
Chapter 1 1
 
Object Modeling Techniques
Object Modeling TechniquesObject Modeling Techniques
Object Modeling Techniques
 
System Programming- Unit I
System Programming- Unit ISystem Programming- Unit I
System Programming- Unit I
 
Data types
Data typesData types
Data types
 
Role-of-lexical-analysis
Role-of-lexical-analysisRole-of-lexical-analysis
Role-of-lexical-analysis
 

Destaque

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
 

Destaque (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
 

Semelhante a Chapter 8 Principles of Programming Languages Subprograms

Semelhante a 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
 

Mais de 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
 

Mais de 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
 

Último

Call Girls Service Chandigarh Lucky ❤️ 7710465962 Independent Call Girls In C...
Call Girls Service Chandigarh Lucky ❤️ 7710465962 Independent Call Girls In C...Call Girls Service Chandigarh Lucky ❤️ 7710465962 Independent Call Girls In C...
Call Girls Service Chandigarh Lucky ❤️ 7710465962 Independent Call Girls In C...Sheetaleventcompany
 
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...aditipandeya
 
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607dollysharma2066
 
Hot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night Stand
Hot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night StandHot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night Stand
Hot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night Standkumarajju5765
 
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Call Girls in Mayur Vihar ✔️ 9711199171 ✔️ Delhi ✔️ Enjoy Call Girls With Our...
Call Girls in Mayur Vihar ✔️ 9711199171 ✔️ Delhi ✔️ Enjoy Call Girls With Our...Call Girls in Mayur Vihar ✔️ 9711199171 ✔️ Delhi ✔️ Enjoy Call Girls With Our...
Call Girls in Mayur Vihar ✔️ 9711199171 ✔️ Delhi ✔️ Enjoy Call Girls With Our...sonatiwari757
 
Enjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort Service
Enjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort ServiceEnjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort Service
Enjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort ServiceDelhi Call girls
 
✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663
✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663
✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663Call Girls Mumbai
 
SEO Growth Program-Digital optimization Specialist
SEO Growth Program-Digital optimization SpecialistSEO Growth Program-Digital optimization Specialist
SEO Growth Program-Digital optimization SpecialistKHM Anwar
 
Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark Web
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark WebGDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark Web
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark WebJames Anderson
 
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...Neha Pandey
 
Challengers I Told Ya ShirtChallengers I Told Ya Shirt
Challengers I Told Ya ShirtChallengers I Told Ya ShirtChallengers I Told Ya ShirtChallengers I Told Ya Shirt
Challengers I Told Ya ShirtChallengers I Told Ya Shirtrahman018755
 
Lucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRL
Lucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRLLucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRL
Lucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRLimonikaupta
 
On Starlink, presented by Geoff Huston at NZNOG 2024
On Starlink, presented by Geoff Huston at NZNOG 2024On Starlink, presented by Geoff Huston at NZNOG 2024
On Starlink, presented by Geoff Huston at NZNOG 2024APNIC
 
Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Hot Service (+9316020077 ) Goa Call Girls Real Photos and Genuine Service
Hot Service (+9316020077 ) Goa  Call Girls Real Photos and Genuine ServiceHot Service (+9316020077 ) Goa  Call Girls Real Photos and Genuine Service
Hot Service (+9316020077 ) Goa Call Girls Real Photos and Genuine Servicesexy call girls service in goa
 
AWS Community DAY Albertini-Ellan Cloud Security (1).pptx
AWS Community DAY Albertini-Ellan Cloud Security (1).pptxAWS Community DAY Albertini-Ellan Cloud Security (1).pptx
AWS Community DAY Albertini-Ellan Cloud Security (1).pptxellan12
 

Último (20)

Call Girls Service Chandigarh Lucky ❤️ 7710465962 Independent Call Girls In C...
Call Girls Service Chandigarh Lucky ❤️ 7710465962 Independent Call Girls In C...Call Girls Service Chandigarh Lucky ❤️ 7710465962 Independent Call Girls In C...
Call Girls Service Chandigarh Lucky ❤️ 7710465962 Independent Call Girls In C...
 
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...
 
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
 
Hot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night Stand
Hot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night StandHot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night Stand
Hot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night Stand
 
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝
 
Call Girls in Mayur Vihar ✔️ 9711199171 ✔️ Delhi ✔️ Enjoy Call Girls With Our...
Call Girls in Mayur Vihar ✔️ 9711199171 ✔️ Delhi ✔️ Enjoy Call Girls With Our...Call Girls in Mayur Vihar ✔️ 9711199171 ✔️ Delhi ✔️ Enjoy Call Girls With Our...
Call Girls in Mayur Vihar ✔️ 9711199171 ✔️ Delhi ✔️ Enjoy Call Girls With Our...
 
Enjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort Service
Enjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort ServiceEnjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort Service
Enjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort Service
 
✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663
✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663
✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663
 
SEO Growth Program-Digital optimization Specialist
SEO Growth Program-Digital optimization SpecialistSEO Growth Program-Digital optimization Specialist
SEO Growth Program-Digital optimization Specialist
 
Rohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No AdvanceRohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
 
Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝
 
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark Web
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark WebGDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark Web
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark Web
 
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
 
Call Girls In Noida 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SERVICE
Call Girls In Noida 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SERVICECall Girls In Noida 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SERVICE
Call Girls In Noida 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SERVICE
 
Challengers I Told Ya ShirtChallengers I Told Ya Shirt
Challengers I Told Ya ShirtChallengers I Told Ya ShirtChallengers I Told Ya ShirtChallengers I Told Ya Shirt
Challengers I Told Ya ShirtChallengers I Told Ya Shirt
 
Lucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRL
Lucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRLLucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRL
Lucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRL
 
On Starlink, presented by Geoff Huston at NZNOG 2024
On Starlink, presented by Geoff Huston at NZNOG 2024On Starlink, presented by Geoff Huston at NZNOG 2024
On Starlink, presented by Geoff Huston at NZNOG 2024
 
Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝
 
Hot Service (+9316020077 ) Goa Call Girls Real Photos and Genuine Service
Hot Service (+9316020077 ) Goa  Call Girls Real Photos and Genuine ServiceHot Service (+9316020077 ) Goa  Call Girls Real Photos and Genuine Service
Hot Service (+9316020077 ) Goa Call Girls Real Photos and Genuine Service
 
AWS Community DAY Albertini-Ellan Cloud Security (1).pptx
AWS Community DAY Albertini-Ellan Cloud Security (1).pptxAWS Community DAY Albertini-Ellan Cloud Security (1).pptx
AWS Community DAY Albertini-Ellan Cloud Security (1).pptx
 

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