KEMBAR78
Chapter8 Subroutines PP | PDF | Parameter (Computer Programming) | Pointer (Computer Programming)
0% found this document useful (0 votes)
6 views27 pages

Chapter8 Subroutines PP

Chapter 9 discusses subroutines and control abstraction in programming languages, emphasizing the importance of abstraction in reducing complexity and facilitating efficient software design. It covers topics such as memory layout, calling sequences, parameter passing methods, exception handling, coroutines, and event types. The chapter highlights how subroutines serve as key building blocks for control abstractions and the various techniques for managing parameters and exceptions in programming.

Uploaded by

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

Chapter8 Subroutines PP

Chapter 9 discusses subroutines and control abstraction in programming languages, emphasizing the importance of abstraction in reducing complexity and facilitating efficient software design. It covers topics such as memory layout, calling sequences, parameter passing methods, exception handling, coroutines, and event types. The chapter highlights how subroutines serve as key building blocks for control abstractions and the various techniques for managing parameters and exceptions in programming.

Uploaded by

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

Chapter 9 :: Subroutines and

Control Abstraction

•CSE307/526: Principles of Programming Languages


•https://ppawar.github.io/CSE307-F18/index.html

Programming Language Pragmatics, Fourth Edition


Michael L. Scott

Copyright © 2016 Elsevier


Abstractions as program building blocks

• Programming is about building abstractions


• Abstraction allows representing essential features without
background details
• Abstraction reduces complexity and allows efficient
design and implementation of complex software systems
• The purpose of control abstraction is to perform a well
defined operation
• Subroutines are the main method to build control
abstractions
• The other form of abstraction we normally think about is
data abstraction – OOP (next topic)
Outline

• Introduction to subroutines
• Review of stack layout
• Calling sequences
• Parameter passing
• Generic subroutines and modules
• Exception handling
• Coroutines
• Events
Outline

• Introduction to subroutines
• Review of stack layout
• Calling sequences
• Parameter passing
• Generic subroutines and modules
• Exception handling
• Coroutines
• Events
Subroutines

• Why use subroutines?


–Give a name to a task.
–We no longer care how the task is done.
• The subroutine call is an expression
–Subroutines take arguments (in the formal parameters)
–Values are placed into variables (actual
parameters/arguments), and
–A value is (usually) returned
• Activation record or stack frames is a means to manage the
space for local variables allocated to each subroutine call
(Chapter 3)
Review Of Memory Layout
• Memory allocation strategies
– Static (compile time)
• Code
• Globals
• Own variables
• Explicit constants (including strings, sets, other aggregates)
– Stack (run time)
• parameters
• local variables
• temporaries
• bookkeeping information
– Heap
• dynamic allocation
Recap – Stack based allocation of
space for subroutines
Recap – Static link
Static links and Dynamic links
Calling Sequences
• Maintenance of stack is responsibility of calling sequence and
subroutines prolog and epilog – discussed in Chapter 3
• Tasks on the way to a subroutine: Passing parameters, saving the return
address, changing program counter, changing stack pointer to allocate
space, saving registers such as frame pointer, changing frame pointer to
refer to new frame, executing initialization code for any objects in the
new frame
• Tasks on the way out from a subroutine: Passing return parameters,
restoring stack pointer, restoring other registers such as frame pointer,
restoring program counter
• space is saved by putting as much in the prolog and epilog as
possible
• time may be saved by putting stuff in the caller instead
In-line expansion
• Alternative to stack-based calling conventions
• During compile time, the compiler replaces a subroutine
call with the code of the subroutine.
• Advantages:
–Avoids overhead associated with subroutine calls; faster code.
–Encourages building abstractions in the form of many small
subroutines.
–Related to but cleaner than macros.
• Disadvantages:
–Code bloating
–Cannot be used for recursive subroutines.
–Code profiling becomes more difficult.
Parameter Passing
• Modes of passing parameters:
–Pass by value: make a copy of the parameter.
–Pass by reference (aliasing): allows the function
to change the parameter
–Pass by sharing: requires parameter to be a
reference itself.
•Makes copy of reference that initially refers to the
same object.
•Within subroutine, value of the object can be changed.
•However, identity of the object can not be changed.
•E.g., User defined Java Objects.
Parameter Passing

def f(a): def f(a): z = object()


a += 1 a.foo = 1 z.foo = 1
x=0 x = object() def f(a):
f(x) x.foo = 0 a=z
print(x) f(x) x = object()
print x.foo x.foo = 0
 value: 0 f(x)
 reference: 1 •value: 0 print x.foo
 sharing: 0 •reference: 1
•sharing: 1 (value •value: 0
change) •reference: 1
•sharing: 0
(identity change)
Parameter Passing
• C/C++ functions
– parameters passed by value (C)
– parameters passed by reference can be simulated with
pointers (C)
void proc(int* x,int y){*x = *x+y } …
proc(&a,b);
– or directly passed by reference (C++)
void proc(int& x, int y) {x = x + y }
proc(a,b);
• Java
– Java uses call-by-value for variables of built-in type (all
of which are values)
– Call-by-sharing for variables of user-defined class types
(all of which are references).
Parameter Passing – Named Parameters
•The values are passed by associating each one with a parameter
name.
•E.g.,in Objective-C:
[window addNewControlWithTitle:@"Title"
xPosition:20
yPosition:50
width:100
height:50
drawingNow:YES];
•E.g.,in Python:
window.addNewControl(title="Title",
xPosition=20,
yPosition=50,
width=100,
height=50,
drawingNow=true)
Parameter Passing – Default Parameters

•Default parameters: default values are provided to the


function
–C++ example:
void PrintValues(int nValue1, int nValue2=10){
using namespace std;
cout << "1st value: " << nValue1 << endl;
cout << "2nd value: " << nValue2 << endl;
}
int main(){
PrintValues(1);
// nValue2 will use default parameter of 10

PrintValues(3, 4);
// override default value for nValue2
}
Parameter Passing – Variadic functions

• functions of indefinite arity – one which accepts variable


number of arguments
•Java
public class Program {
private static void printArgs(String... strings) {
for (int i = 0; i < strings.length; i++) {
String string = strings[i];
System.out.printf("Argument %d: %s", i, string);
}
}

public static void main(String[] args) {


printArgs("hello", "world");
}
}
Subroutine closures as parameters

• A closure is a reference to subroutine may be passed as a


parameter
• Languages that support this:
–Pascal
–Ada 95 (not Ada 83)
–All functional programming languages
• SML example
fun apply_to_L(f, l) =
case l of
nil => nil
| h :: t => f(h) :: apply_to_L(f, t);
Parameter Passing
Returning from a function
• Different ways of returning a value from a function.
–Return statement
return expression (causes immediate termination of function)
–Avoid termination
rtn := expression
...
return rtn
• ML, its descendants, and several scripting languages allow a
Multi-value returns
• In Python, for example, we might write
def foo():
return 2, 3
...
i, j = foo()
Generic subroutines and modules
• Generic modules or classes are particularly valuable for creating containers:
data abstractions that hold a collection of objects
–When defining a function, we don't need to give all the types
–When we invoke the class or function we specify the type: parametric
polymorphism
• Generic subroutines (methods) are needed in generic modules (classes), and
may also be useful in their own right
public static <T extends Comparable<T>> void sort(T A[]) {
...
if (A[i].compareTo(A[j]) >= 0) {
...
}
...
}
Integer[] myArray = new Integer[50];
sort(myArray);
Exception Handling
• What is an exception?
– a hardware-detected run-time error or unusual condition detected by
software
• Examples
– arithmetic overflow
– end-of-file on input
– wrong type for input data
– user-defined conditions, not necessarily errors
• Raising exceptions:
–Automatically by the run-time system as a result of an abnormal
condition
–(e.g., division by zero)
–throw/raise statement to raise exceptions manually
–Most languages allow exceptions to be handled locally and propagate
unhandled exceptions up the dynamic chain.
Exception Handling

• What is an exception handler?


– code executed when exception occurs
– may need a different handler for each type of exception
• Why design in exception handling facilities?
– allow user to explicitly handle errors in a uniform manner
– allow user to handle errors without having to check these
conditions explicitly in the program everywhere they might
occur
Exception Handling
• Java:
try {
–throw throws an exception. ...
–try encloses a protected block. throw ...
...
–catch defines an exception handler. }
catch (SomeException e1) {
–finally defines block of clean-up code to ...
execute no matter what. }
catch (SomeException e2) {
–Only Throwable objects can be thrown. ...
}
–Must declare uncaught checked exceptions. finally {
...
• C++: }
–throw, try, and catch as in Java
–No finally block
–Any object can be thrown.
–Exception declarations on functions not
required
Coroutines
• Coroutines are execution contexts that exist concurrently, but that execute
one at a time, and that transfer control to each other voluntarily and
explicitly, by name
• Coroutines can be used to implement
– iterators
– threads
– Because they are concurrent (i.e., simultaneously started but not
completed), coroutines cannot share a single stack
– But they may use static link for scoping
Event types

• An event is something to which a running program (a


process) needs to respond, but which occurs outside
the program, at an unpredictable time.
–The most common events are inputs to a graphical user interface
(GUI) system: keystrokes, mouse motions, button clicks.
–They may also be network operations or other asynchronous I/O
activity: the arrival of a message, the completion of a previously
requested disk operation
• A handler—a special subroutine— is invoked when a given
event occurs.
• Thread-Based Handlers:
–In modern programming languages and run-time systems, events are
often handled by a separate thread of control, rather than by
spontaneous subroutine calls
Event types

You might also like