Procedures and Functions · Cambridge syllabus 8.1 · Lesson 2 of 3
Functions
A function accepts parameters, performs a calculation and returns a value that can be used in another expression. Distinguish returning a value from displaying it; a caller decides what to do with the result.
By the end, you can
- Understand the purpose of a function.
- Define and call functions.
- Use up to three parameters, each with its data type.
- Return a value from a function.
- Use returned values in expressions.
Functions
A function is like a procedure except that it returns a value to the point where it was called. FUNCTION Area(Width : INTEGER, Height : INTEGER) RETURNS INTEGER, with RETURN Width * Height inside, and ENDFUNCTION. Like a procedure, it can have up to three parameters, each with its data type, and the data type of the value it returns is stated after RETURNS.
Because it returns a value, a call to a function is part of an expression rather than a statement on its own, and it is never called with CALL. It can appear anywhere a value can: Total ← Area(3, 4) + Area(5, 6), or IF Area(Width, Height) > 100, or directly inside an OUTPUT statement. A procedure call cannot be used that way, and that is the whole difference between them.
RETURN ends the function immediately and sends the value back, so any statements after it in that path never run. A function should return on every path through it, or some call will produce nothing.
The useful discipline is to keep a function free of side effects: it takes its inputs as parameters, calculates, and returns an answer, without changing global variables or printing anything. A function written that way can be tested on its own by calling it with known values and checking what comes back, and it behaves the same wherever it is used.
Choosing between the two is straightforward: if the caller needs an answer, write a function; if the caller needs something done, write a procedure. Calculate a total, convert a temperature and check whether a string is valid are functions; print a report, save a file and clear the screen are procedures.
Worth remembering
- A function returns a value, so a call to it is an expression.
- RETURN ends the function at once; every path should return something.
- Needs an answer: function. Needs something done: procedure.
Worked example
FUNCTION Double(Value : INTEGER) RETURNS INTEGER contains RETURN Value * 2. Result ← Double(6) stores 12.
Practice
Warm-up · not marked
Check your understanding
Answer in your own words, then compare with the worked answer. Nothing here is saved or scored.
Worked answer
25.
Check your method, units and explanation against it.
Marked practice
Set 1 of 5 · easiest first · Checked as you go, with the worked answer. Sign in or create a free account to save your progress.