You are on page 1of 6

ITECH5403 Comparative Programming Languages

School of Science, Engineering and Information Technology

Lab 10 – Subprograms
Introduction

As this is an 'even' week we'll be experimenting with programming languages – in this lab it'll be the
Perl scripting language. First introduced in 1987, Perl is a mature and powerful programming language
which has been called the ‘Swiss-army chainsaw of programming’ or ‘The duct-tape that holds the
Internet together’ due to its common use in scripted administrative tasks and text manipulation.

Once we've spent a little bit of time getting to grips with Perl, there'll be some theory questions &
problems on this weeks' topic of subprograms.

Remember – in these labs you aren't expected to know every single answer from memory – sometimes
it's best to do a little research / reading / re-reading of materials and come up with a great, and
correct, answer rather than just 'taking a stab' at the question and hoping you're right!

Learning Perl

The tutorial we’ll use for this lab is hosted at: http://www.learn-perl.org/ and your job for the first part of
this lab is to go through the sections from ‘Hello, World!’ down to ‘Subroutines’ in the tutorial.

To do this you don’t even have to install Perl to a local machine, because there is an interactive Perl
interpreter built right into the website!

Later on if you decide to use Perl for one of your implementations of the second assignment (you have
a choice between Perl and Lisp), then you can install Strawberry Perl (http://strawberryperl.com) in
order to work from .pl files rather than working with the interactive interpreter like you’ll be doing today.

Perl isn’t an especially pretty language but it’s very powerful, commonly used, and has a great range of
features whereby you can get a lot of work done with a relatively small amount of code. Have a play
with it and see what you think!

CRICOS Provider No. 00103D Insert file name here Page 1 of 6


Review Questions

1. What are the three general characteristics of subprograms? [Q1]

In general, subprograms have the following three characteristics:

- Each subprogram has a single entry point,


- The calling program unit (i.e. the piece of code that calls the subprogram) is suspended during the
execution of the subprogram, which implies that there is only one subprogram in execution at any
given time.
- Control always returns to the caller when the subprogram execution terminates.

Subprograms which do not have the above characteristics, and as such work differently, are called co-routines or
concurrent units.

2. What is given in the protocol / contract of a subprogram? [Q3-Mod]

The protocol, or contract, of a subprogram defines:

- The name of the subprogram (i.e. drawModel),


- The parameter types and names given to the parameters (i.e. float linewidth) as well as the order in
which the arguments must be supplied (there may also be default values specified for arguments, if
applicable in the programming language)
- The return type of the subprogram (i.e. void, int, float, etc.)

For example – if we look at the protocol of a hypothetical drawModel method:

void drawModel(Mat4f modelViewProjectionMatrix, float lineWidth, int scale)

The method returns void (i.e. nothing is returned), it's called drawModel, and it takes a Mat4f object which we
will refer to as modelViewProjectionMatrix, followed by a float which we will refer to as lineWidth, followed by
an int which we will refer to as scale (arguments must be provided to the method in that exact order!).

3. With regard to subprograms, what are formal parameters? What are actual parameters? [Q8]

Formal parameters are the list of data types and their names in a given order, and are commonly just called
parameters.

Actual parameters are the elements of data passed to a function itself, and are commonly called arguments.

4. What are the differences between a function and a procedure? Give a simple example of a
function and a procedure which result in the same outcome. [Q10-Mod]

There are two distinct categories of subprograms - procedures and functions, the difference between them is that
functions return values and procedures do not.

As procedures are enacted by single call statements, in effect, procedures can be thought of as defining new
statements! For example, if a language does not have a sort statement, then a user can build a procedure to sort
arrays of data and use a call to that procedure.

CRICOS Provider No. 00103D Page 2 of 6


An example of a function and a procedure which produce the same outcome (in C++) is:

// global int
int myValue = 5;

// Function – returns value


int multiplyByTwoFunc(int theValue) { return theValue * 2; }
myValue = multiplyByTwoFunc(myValue); // Call the function to double the value

// Procedure
void multiplyByTwoProc(int &theValue) { theValue *= 2; }
multiplyByTwoProc(myValue); // Call the procedure to double the value

5. Describe the advantages and disadvantages of dynamic local variables and static local
variables. [Q12/13]

Dynamic local variables:

Advantages: Allow for flexibility i.e. you can create variables or data structures as required, typically
created on the stack so quick to allocate, therefore de-allocation occurs automatically when the scope ends.

Disadvantages: Some time is required to allocate the memory, initialise the variables, and then release the
memory when the scope ends. Data types may not be determined until runtime, which allows for the
possibility of type errors.

Static local variables:

Advantages: Memory allocation only occurs once at the beginning of the program, so there is no constant
setup and tear-down of variables created inside functions which are constantly being called. Type checking
can occur at compile time rather than at runtime, which will help to eliminate any potential type errors.

Disadvantages: Can be a little confusing to work with, because the creation and initialisation only happens
once so you (as a programmer) have to look at the code and realise that the initialisation will only occur
once and that the create/initialise line will be skipped on all further executions of the method defining the
static local variable. Also, you have to remember to release the memory at the end of the program if the
variable/object/structure was allocated on the heap.

6. Explain the operation of the following methods of parameter passing, providing at least one
example of each: [Q16-Mod]
- Pass-by-value,
- Pass-by-result,
- Pass-by-value-result, and
- Pass-by-reference.

When a parameter is passed by value, the value of the actual parameter is used to initialise the corresponding
formal parameter, which then acts as a local variable in the subprogram. In essence, the function works with a

CRICOS Provider No. 00103D Page 3 of 6


copy of the data, and any changes made to the copy are just that – changes made to the copy – the original
remains unchanged. This corresponds to in mode semantics.

When a parameter is passed by result, no value is transmitted to the subprogram - instead, the corresponding
formal parameter acts as a local variable, but just before control is transferred back to the caller, its value is
transmitted back to the caller's actual parameter (which obviously must be a variable!). This corresponds to out
mode semantics.

Pass-by-value-result is an implementation model for inout mode parameters in which actual values are copied.
In effect, it is a combination of pass-by-value and pass-by-result. The value of the actual parameter is used to
initialise the corresponding formal parameter, which then acts as a local variable. In fact, pass-by-value-result
formal parameters must have local storage associated with the called subprogram. Then, at subprogram
termination, the value of the formal parameter is transmitted back to the actual parameter. Pass-by-value-result
is sometimes called pass-by-copy because the actual parameter is copied to the formal parameter at subprogram
entry, and is then copied back at subprogram termination.

Pass-by-reference is a second implementation model for inout mode parameters. Rather than copy data values
back and forth, as in in pass-by-value-result, the pass-by-reference method transmits an access path - i.e. a
memory address to the called subprogram. This provides the subprogram with a means to access the actual
parameter directly without having to copy it at all!

7. With regard to nested subprograms, explain the concepts of: [Q23-Mod]


- Shallow binding,
- Deep binding, and
- Ad-Hoc Binding.

When working with nested subprograms – there are three main choices for which referencing environment is
used for the nested subprogram. The choices are:

- Shallow binding, where the environment of the call statement that executes the passed subprogram
is used.

- Deep binding, where the environment of the definition of the passed subprogram is used, and

- Ad-hoc binding, where the environment of the call statement that passed the subprogram as an
actual parameter is used.

8. Explain what a closure is and what features of closures make them useful? [Q34/35]

A closure 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.

If a static-scoped programming language does not allow nested subprograms, closures are not useful - so such
languages do no support them.

When subprograms can be nested, in addition to locals and globals, the referencing environment of a
subprogram can include variables defined in all enclosing subprograms! Nearly all functional programming
languages, most scripting languages and at least one primarily imperative language (C#) support closures.

CRICOS Provider No. 00103D Page 4 of 6


Problem Set

1. What are the arguments for and against allowing overloading of operators? [PS1-Mod]

Allowing overloading of operators allows the programmer to use operators in a natural way with their own
custom classes and objects. For example, you could write overloaded addition and subtraction operators for a
custom BankAccount class, which would allow you to add two bank accounts together, or subtract one from
another, in a very simple manner such as:

BankAccount combinedAcount = husbandAccount + wifeAccount;

However, the flexibility also means that it's possible to write overloaded operators which make no sense. You
could, for example, write overloaded operators to legally a Car object to be multiplied by a Banana object – it
would be legal but what would this even mean?

Also, if a separate programmer is working with code with overloaded operators, or the same programmer after
some time away from the code – they might not know that the operators are overloaded and that they might
function in a different manner to what might be expected.

Further, you could legally make 'bad' operators, such as making the + operator subtract, and the / operator
multiply! Or, there might be side effects introduced in the operators which do not occur in standard operators,
which may lead to subtle but serious problems with the code.

Overall I feel that overloaded operators are a powerful addition to a programming language, but one which
should be used rarely, and with care.

2. Consider the following program written in C syntax: [PS7]

void fun (int first, int second) {


first += first;
second += second;
}
void main() {
int list[2] = {1, 3};
fun(list[0], list[1]);
}

For each of the following parameter-passing methods, what are the values of the list array after
execution?
a. Passed by value
b. Passed by reference
c. Passed by value-result

Passed by value: 1, 3 (only the COPIES are modified)

Passed by reference: 2, 6 (the REFERENCES to the original values are modified, therefore the original values in
the list are modified)

Pass by value-result: 2, 6 (the values are COPIED in, but are then also COPIED out back into the list elements)

CRICOS Provider No. 00103D Page 5 of 6


3. Explain how pass-by-name parameters operate, and provide at least one example of a
common use of the pass-by-name mechanism. [PS15-Mod]

Pass-by-name is an inout mode parameter transmission method that does not correspond to a single
implementation model. When parameters are passed by name, the actual parameter is, in effect, textually
substituted for the corresponding formal parameter in all its occurrences in the subprogram.

Implementing pass-by-name requires a subprogram to be passed to the called subprogram to evaluate the
address or value of the formal parameter… and this subprogram plus referencing environment is called a
closure. Pass-by-name parameters are both complex to implement and inefficient - but there are occasional times
when it comes in useful, such as in preprocessors.

4. Speculate on the issue of allowing nested subprograms in programming languages - why are
they not allowed in many modern languages? [PS14-Mod]

Nested subprograms allow specific subprograms to be "hidden" from the rest of the codebase, lowering the
number of potential interactions (i.e. a nested method may only be called from the method in which it is actually
nested).

Nested functions can be used to make a program easier to read and understand, by cutting down on the amount of
explicit parameter passing without introducing lots of global state - however, the type of referencing environment
made available to the nested subprogram can affect the usefulness of the nested subprogram itself.

Further, nested subprograms promote global data and tight coupling – that is, they create pockets of functionality
without a good mechanism to extend their reach. For example if someone creates a nested function whose
operations are needed later in a different scope they may find it is easier to make data global rather than
restructuring the function to operate on private data.

Many modern languages don't allow nested subprograms because it adds complexity to the language for a
relatively small gain. No language must have nested subprograms to function, or to put it another way, any
language that can perform a given task can do so without the use of nested subprograms. As such, language
designers may see them as an additional feature / level of complexity which does not justify inclusion in the
language.

CRICOS Provider No. 00103D Page 6 of 6

You might also like