4. Subroutine and Function
A module is broken down into a set of procedures. These procedures require data of some kind to pass into them and data may need to pass back to the calling routine in some way.
There are two kind of procedures, each very similar in purpose but subtly different
Subroutine
A subroutine is a procedure that can take zero or more values as input, act upon that data, then return zero, one or more values. A couple of examples makes this clearer.
procedure DisplayGraphics(MonitorType,HighestResolution) {
-----
----
return resolution_set
}
A subroutine called 'DisplayGraphics' has the task of setting the current monitor to a given resolution. It has two 'arguments' or 'parameters' passed into it. The first defines the current monitor in use, the second argument is a 'flag' to tell it to set it to the maximum resolution, whatever that may be. A 'flag' is a specific value that defines what needs to be done within the subroutine, in this case it is telling the subroutine to set the given monitor to its maximum resolution.
The subroutine returns zero or more values, in this case it does return a value to the calling procedure.
Another subroutine might have no argument or parameter at all, as it obtains its data by other means
procedure PrintCurrentOpenDocument() {
---
return }
In this case the subroutine 'knows' what document is currently open (this is explained in the global variables page). It also does not return any value. It simply does its job of printing the document. (Not normally a good idea, as it should at least say if it succeeded or not)
A subroutine is always 'called'. Calling a subroutine means the calling procedure sets up the CPU to carry out the instructions within the subroutine.
For example, the example subroutine could be called thus:
y = DisplayGraphics("LG Flatron", 1);
The string LG Flatron is the name of the monitor, whilst 1 flags that the maximum resolution is to be used (it could have been anything else of course, it just depends on the internal code of the subroutine).
Function
This is similar to a subroutine but it only ever returns one value. Again a few examples clarify this
y = SIN(x)
day = Day_I_was_Born(24,11,57);
The first function called SIN works out the sine of x. A single value is returned and stored in y.
The function 'Day_I_was_Born() takes a day, a month, a year and returns the day of the week that happened.
Again only a single value was returned. A function is just like those you find on a calculator only it does not have to be just maths!
Key terms to understand
- Subroutine
- Function
- Parameter
- Argument
- Flag
Challenge see if you can find out one extra fact on this topic that we haven't already told you
Click on this link: Using subroutines
Copyright © www.teach-ict.com