Subprogram
Introduction
Procedure & Function
- Subprograms are collections of statements that define parameterized computations
- There are two kinds of subprograms:
- Functions return values
- Procedure do not
- In most of the languages do not include procedures as a separate form of subprogram (functions that can be defined not to return values can be used as procedures)
Execution
- Each subprogram has a single entry point
- The calling subprogram is suspended during execution of the called subprogram (i.e., there is only one subprogram in execution in the given time)
- Except the program is terminated, control always return to the caller at the subprogram called statement when the called subprogram’s execution terminate
Definition
Subprogram Definition
describes the interface to and the actions of the subprogram abstraction
1
2
3
4void f(){
cout << "haha" << endl;
return;
}fis the definition of this subprogram
In Python, function definitions are executable
- In all other languages, they are non-executable
- Executable function definition:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17is_advanced_operator_allowed = True
if is_advanced_operator_allowed:
def is_even(n):
print("thinking...")
return n % 2 == 0
else:
def is_even(n):
print("thinking...")
if n == 1:
return False
elif n == 2:
return True
else:
return is_even(n-2)
print(is_even(10))
- Subprogram Call
- an explicit request that the subprogram be executed (
fun())
- an explicit request that the subprogram be executed (
- Subprogram Header
- the first part of the definition, including the name, the kind of subprogram, and the parameters
- Parameter Profile
- the number, order, and types of its parameters
- Protocol
- the parameter profile and the return type
- Subprogram Declaration
- the protocol of the subprogram (prototype in C/C++)
1
int sum(int, int);
- the protocol of the subprogram (prototype in C/C++)
- Parameter (formal parameter)
- a variable listed in the subprogram header and used in the subprogram
1
int sum(int a, int b) { } // a and b are the parameters
- a variable listed in the subprogram header and used in the subprogram
- Argument (actual parameter)
- the actual input supplied in the subprogram call statement to the subprogram
1
sum(14, 23) // arguments
- the actual input supplied in the subprogram call statement to the subprogram
Correspondence
Positional
- the binding of arguments to parameters is by position
- Advantage: Simple and effective
Keyword (in Python, JavaScript, C#)
- the name of the parameter is in form of a keyword, to which an argument is to be bound is specified with the argument
1
2
3
4
5
6
7def f(a, b, c):
print("a is", a)
print("b is", b)
print("c is", c)
f(b=1, a=2, c=3)
f(3, c=9, b=1) - Advantage: arguments can appear in different order
- Disadvantage: users are able to know the parameter’s names
- the name of the parameter is in form of a keyword, to which an argument is to be bound is specified with the argument
Parameter Default Values
- parameters can have default values if no argument is passed
- Note: the default parameters must appear last(because parameters are positionally associated)
Remind: the default parameters should be assign in subprogram declaration (if have)
default parameter in C++
1
2
3
4
5
6
7
8
9int sum(int, int = 3);
int main() {
cout << sum(1) << endl; // 4
}
int sum(int a, int b){
return a + b;
}list of variable number of parameters in Python (
*)1
2
3
4
5def fun(x, *args):
print(type(args)) # tuple
print(x, args) # 1, (2, 3, "dq")
fun(1, 2, 3, "dq")named keyword argument in Python (
**)1
2
3
4
5
6
7def fun(**args):
print(type(args)) # dict
for key, value in args.items():
print(key, "->", value) # name -> doge
# age -> 17
fun(name = "doge", age = 17)
Parameter Passing Methods
Passing Value
Pass-by-Value
- the value of the argument is used to initialize the corresponding parameter
- normally implemented by simply copying
1
2
3
4
5
6
7
8int sum(int a, int b){
return a + b;
}
int main() {
int a = 3;
int b = 5;
cout << sum(a, b) << endl;
} - Advantage: no side-effect
- Disadvantage: require additional storage
Pass-by-Result
- no value is transmitted to the subprogram, the parameter simply acts as a local variable
- i.e., the value is transmitted to the caller’s argument when control return to the caller by coping
1
2
3
4
5
6
7
8
9subroutine foo(result x)
x = x * 2
end subroutine
main
variable a = 3
call foo(a)
print a // prints 6
end main - Potential problem:
call foo(a, a): in this case, what should a be?
Pass-by-Value-Result
- combination of pass-by-value and pass-by-result
- i.e., copying the value of argument to the parameter, then do some change on the parameter in the subprogram, then copying the value of parameter to the argument when return
- Disadvantage: combination of pass-by-value and pass-by-result
Passing Object
Pass-by-Reference
- pass the reference to the argument variable (can be simulated in pass-by-value of pointers for languages that not support reference)
- copying the address of arguments instead of the whole data structure
1
2
3
4
5
6
7
8
9
10void f(int& a){
a = 99;
return;
}
int main(){
int b = 0;
f(b);
cout << b << endl;
}
- copying the address of arguments instead of the whole data structure
- Advantage: passing is efficient because there is no copying and duplicate storage
- Disadvantage:
- slower access (indirect access)
- potential for the side effect
- pass the reference to the argument variable (can be simulated in pass-by-value of pointers for languages that not support reference)
Pass-by-Sharing
- copy the reference argument (point to an object) and pass to the parameter
- Note: it is for object only (so need to wrapper the primitive data values in we want to use Pass-by-Sharing in those values)
- Python / Ruby use Pass-by-Sharing
Everything is concidered as an object (all variables are considered as references to some objects) - Java also use pass-by-sharing for object arguments
Consider Pass-by-Sharing is just similar to Pass-by-value (copying), so simply use Pass-by-Value (where the value is a reference)
Pass-by-Renerence vs Pass-by-Sharing

Implementation of Pass-by-Renerence (similated using pointer) in C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17class Dog{
public:
string name;
Dog(string name): name(name) {};
};
void fun(Dog*& d){ // & - reference Dog* a pointer to Dog type
d->name = "corgi";
d = new Dog("shiba");
}
int main(){
Dog* d = new Dog("husky");
fun(d); // passing-by-reference
cout << d->name << endl; // outputs: shiba
return 0;
}Implementation of Pass-by-Sharing in Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19class Dog{
public String name;
Dog(String name){
this.name = name;
}
}
class Hello {
public static void fun(Dog d){
d.name = "corgi";
d = new Dog("shiba");
}
public static void main(String[] args){
Dog d = new Dog("husky");
fun(d); // passing-by-sharing
System.out.println(d.name); // outputs: corgi
}
}- The main different is the new assignment for the parameter in the subprogram:
- Pass-by-Reference is passing a reference to the argument
- Pass-by-Sharing is passing a copied reference from the argument
Therefore, when there is a new assignment to the parameter, the argument is also changed in Pass-by-Reference but not Pass-by-Sharing
Parameters
Multidimensional Arrays
access an element in a multi-dimensional array, a storage mapping function (address calculation) has to be built
int a[4][2] = {{11,12}, {21,22}, {31,32}, {41,42}};Memory Address (One-dimensional) 11 12 21 22 31 32 41 42 ... - address of
a[3][1]= (address ofa[0][0]) + (3 2 + 1) (sizeof int)
- address of
C/C++ Implementation
Porblems:
C/C++ requires programmer to include the declared size of all (but not the first dimension) in the array parameter
- It is necessary for the programmer to declare the parameter like
void f(int a[2][3][8])orvoid f(int a[][3][8])(but not the first dimension)
- It is necessary for the programmer to declare the parameter like
sizeofarray in a function1
2
3
4
5
6
7
8
9void f(int a[10]){
cout << sizeof(a) << endl; // 8
}
int main(){
int a[10] = {1,2,3,4,5,6,7,8,9,0};
cout << sizeof(a) << endl; // 40: 4 * 10
f(a); // 8: sizeof the pointer instead of the array
}
- Solution:
- We can use a flexible workaround
- pass a pointer to the array and the sizes of the dimensions as other parameters
void f(int* a, int firstDSize, int secondDSize, int thirdDSize)
- pass a pointer to the array and the sizes of the dimensions as other parameters
- We can use a flexible workaround
- Java/C#/Python Implementation
- Arrays are objects in those languages, so the multi-dimensional array is single-dimensioned
int a[][] = {{11}, {21,22,23}, {31,32}};Memory Address (One-dimensional) Array Object Array Object Array Object ... 11 21 22 23 31 32 ... - Access the size of array:
l.lengthin Javalen(l)in Python
- Arrays are objects in those languages, so the multi-dimensional array is single-dimensioned
Subprograms
There are situations in which a subprogram is a parameter of another subprogram
C/C++ Implementation
- functions can be passed as function pointers
(*p)(...)1
2
3
4
5
6
7
8
9
10
11void f(int x){
int a, b, c;
cout << "f() is called, " << x << endl;
}
void g(void (*p)(int), int x){
p(x);
}
int main(){
g(f, 3); // f() is called, 3
return 0;
}
- functions can be passed as function pointers
Python Implementation
- functions in Python are first-class citizens and simply objects
so it can be simply passed as parameter like any other Objects1
2
3
4
5
6
7
8
9
10def f(x):
print("f() is called,", x)
def p(x):
print("p() is called,", x + 1)
def g(fun, x):
fun(x)
g(f, 2) # f() is called, 2
g(p, 2) # p() is called, 3
- functions in Python are first-class citizens and simply objects
Closures
- it is a subprogram and the referencing environment where it was defined
- the referencing environment is needed if the subprogram can be called from any arbitrary place in the program
A static-scoped language that does not permit nested subprograms doesn’t need closures
- Implementation in C++:
1
2
3
4
5
6
7
8
9
10
11
12
13int global_var = 4;
void f(){
int a = 1, b = 2, c = 3;
cout << "f() is called, local = " << a << ", global = " << global_var << endl;
}
void g(void (*p)()){
p();
}
int main(){
f(); // f() is called, local = 1, global = 4
g(f); // f() is called, local = 1, global = 4
return 0;
}- the referencing environment in f (called from any arbitrary place in the program) is the local variables (
a,b,c) and the global variables which is same as directly calling, so the static-scoped language that does not support nested programming doesn’t need closures
- the referencing environment in f (called from any arbitrary place in the program) is the local variables (
- Implementation in C++:
Closures are necessary for a subprogram that can access variables in the nesting scopes and it can called from abywhere
- Implementation in Python:
1
2
3
4
5
6
7
8def adder(x):
def template_adder(y): # nested subprogram
return x+y
return template_adder
# actually returning a closure that has the referencing environment as adder
add_five = adder(5) # the closures (<function adder.<locals>.template_adder at 0x55dec94ab020>)
print(add_five(2)) # 7- the referencing environment of
template_adderhasxwhich is outside the definition oftemplate_adder, but because Python supports closures, soxis also passed through to thetemplate_adder - the clousre returned from
adderis both the function and the referencing environment
- the referencing environment of
- Implementation in Python:
- closures actually extended lifetime to some variables, in case,
xis extended as the functionadderhas already ended
Lambdas
- anonymous functions (which syntax is much more simplier and readable than defining a function) using the keyword
lambda- Implementation in Python:
1
2
3
4
5def adder(x):
return lambda y: x + y
add_five = adder(5)
print(add_five(2))- In case, the function named
template_adderis not important as it would be “rename” later
(add_five = adder(5): the functiontemplate_adderis actually renamed toadd_five)
- In case, the function named
- Implementation in Python:
Polymorphic Subprograms
- Polymorphic subprograms are subprograms that can operate on different types of data
Adhoc Polymorphism
- Overloaded subprograms provide a particular kind of polymorphism called adhoc polymorphism
1
2
3
4
5
6
7
8
9
10
11
12
13
14void printType(int x){
cout << "int is the best!" << endl;
}
void printType(float x){
cout << "float is the best!" << endl;
}
int main(){
printType(1); // int is the best!
printType(1.0f); // float is the best!
printType(true); // int is the best!
printType(1.0); // ERROR
}
- Overloaded subprograms provide a particular kind of polymorphism called adhoc polymorphism
Subtype Polymorphism
- A parameter of type X can take any object of type X or any type derived from X
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32class Food {
public:
virtual void eat() {
cout << "Eating food." << endl;
}
};
class Apple : public Food {
public:
void eat() {
cout << "Eating apple." << endl;
}
};
class Water : public Food {
public:
void drink() {
cout << "Drinking water." << endl;
}
};
int main() {
Food* food = new Food();
Food* apple = new Apple();
Food* water = new Water();
food->eat(); // Eating food.
apple->eat(); // Eating apple.
water->eat(); // Eating food. (since the Water class doesn't override the eat() method)
return 0;
}


