11.3.2 Functions and Return Values
A function is a named subroutine that produces one value for its caller. Because it produces a value, a function call can appear inside an assignment, calculation, output statement or Boolean expression.
This page focuses on function definitions, calls, return values and local processing. Parameters are introduced where they help explain realistic functions, while detailed parameter-passing mechanisms are developed in 11.3.3.
By the end of this section, you should be able to:
- Define the term function.
- Explain the difference between a procedure and a function.
- Identify a function header, interface, body and end marker.
- Specify the data type returned by a function.
- Write a function containing a suitable
RETURNstatement. - Explain how a returned value replaces a function call.
- Use a function call within an assignment or expression.
- Use functions that return numeric, string or Boolean values.
- Trace parameters, local variables and a returned value.
- Recognise that executing
RETURNimmediately ends the function call. - Choose between a procedure and a function for a given task.
- Avoid unnecessary repeated function calls.
What Is a Function?
A function performs a defined task and sends one result back to the point from which it was called.
Simple function with no parameters
FUNCTION GetDefaultLevel() RETURNS INTEGER
RETURN 4
ENDFUNCTION
The function does not produce output by itself. It produces the integer value 4 for use by the calling expression.
CurrentLevel β GetDefaultLevel()
After the function returns, the assignment behaves as:
CurrentLevel β 4
RETURN 4 sends the value to the caller;
OUTPUT 4 displays it to the user.
Procedure or Function?
| Feature | Procedure | Function |
|---|---|---|
| Primary purpose | Perform a task | Calculate, derive or select a value |
| Returned data value | Not returned directly | Returns one value |
| Typical pseudocode use | CALL DisplayMenu |
Area β CalculateArea(7, 4) |
| Can appear in an expression? | No | Yes |
| Header includes return type? | No | Yes |
| Closing keyword | ENDPROCEDURE |
ENDFUNCTION |
Procedure example
PROCEDURE DisplayMenu
OUTPUT "1. Add record"
OUTPUT "2. Edit record"
OUTPUT "3. Exit"
ENDPROCEDURE
CALL DisplayMenu
Function example
FUNCTION CalculateArea(Width : INTEGER,
Height : INTEGER) RETURNS INTEGER
RETURN Width * Height
ENDFUNCTION
PanelArea β CalculateArea(7, 4)
The Parts of a Function
FUNCTION CalculateArea(Width : REAL,
Height : REAL) RETURNS REAL
DECLARE Area : REAL
Area β Width * Height
RETURN Area
ENDFUNCTION
| Part | Example | Purpose |
|---|---|---|
| Function header |
FUNCTION CalculateArea(...) RETURNS REAL
|
Identifies the function, its inputs and its return type |
| Function name | CalculateArea |
Identifier used in the function call |
| Parameter list | Width : REAL, Height : REAL |
Names the data received by the function |
| Return type | RETURNS REAL |
States the data type of the result |
| Function body | Declaration, calculation and return statement | Contains the processing performed during the call |
| Return statement | RETURN Area |
Sends the result to the caller |
| End marker | ENDFUNCTION |
Marks the end of the definition |
GetDefaultLevel(), not GetDefaultLevel.
The Function Interface
The interface describes how another part of the program can use the function. It includes the function name, its parameters and the type of value returned.
FUNCTION CalculateArea(Width : REAL,
Height : REAL) RETURNS REAL
| Interface element | Meaning |
|---|---|
CalculateArea |
Name used by the caller |
Width : REAL |
First required input |
Height : REAL |
Second required input |
RETURNS REAL |
Type of value produced |
PanelArea β CalculateArea(7.5, 4.2)
In this call, 7.5 and 4.2 are arguments supplied
to the function. Detailed parameter and argument terminology continues in the
next section.
How a Return Value Replaces a Function Call
FUNCTION GetBonus() RETURNS INTEGER
RETURN 6
ENDFUNCTION
FinalScore β 14 + GetBonus()
| Stage | What happens? |
|---|---|
| 1. Call encountered |
Evaluation pauses when the program reaches
GetBonus()
|
| 2. Function executes | The statements in GetBonus run |
| 3. Value returned | The function returns 6 |
| 4. Call replaced |
The expression becomes 14 + 6
|
| 5. Expression completed | FinalScore receives 20 |
Using Function Calls in Expressions
A function call can be placed wherever a value of its return type would be valid.
Assignment
PanelArea β CalculateArea(7, 4)
Arithmetic expression
TotalSpace β ExistingSpace + CalculateArea(7, 4)
Output statement
OUTPUT "Area: ", CalculateArea(7, 4)
Boolean condition
IF IsSafeReading(CurrentReading) = TRUE
THEN
OUTPUT "Reading accepted"
ENDIF
Argument supplied to another function
Category β GetAreaCategory(CalculateArea(7, 4))
CALL CalculateArea(7, 4)
A function call is used as part of an expression. The keyword
CALL is used for procedures.
Function Return Types
The value returned must be compatible with the type declared in the function header.
| Function purpose | Possible return type | Example result |
|---|---|---|
| Count matching records | INTEGER |
12 |
| Calculate an average | REAL |
18.75 |
| Create a status label | STRING |
"Available" |
| Test whether data is acceptable | BOOLEAN |
TRUE |
| Select a single code | CHAR |
'H' |
Boolean function
FUNCTION IsSafeReading(Reading : INTEGER) RETURNS BOOLEAN
RETURN Reading >= 20 AND Reading <= 80
ENDFUNCTION
String function
FUNCTION GetAvailability(InStock : BOOLEAN) RETURNS STRING
IF InStock = TRUE
THEN
RETURN "Available"
ELSE
RETURN "Unavailable"
ENDIF
ENDFUNCTION
RETURNS INTEGER should not return a string such as
"Twelve".
Return Statements and Alternative Paths
A function can contain selection. Every possible execution path should produce an appropriate returned value.
FUNCTION GetTemperatureBand(Temperature : REAL)
RETURNS STRING
IF Temperature < 10
THEN
RETURN "Cold"
ELSE
IF Temperature <= 24
THEN
RETURN "Moderate"
ELSE
RETURN "Warm"
ENDIF
ENDIF
ENDFUNCTION
| Argument | Path followed | Returned value |
|---|---|---|
| 6 | First condition is true | "Cold" |
| 18 | First false; second true | "Moderate" |
| 31 | Both conditions false | "Warm" |
Executing RETURN immediately ends the current function call.
Statements later in the same path are not executed.
Unreachable statement
FUNCTION GetCode() RETURNS CHAR
RETURN 'A'
OUTPUT "This statement cannot run"
ENDFUNCTION
RETURN. Once the return statement executes, control leaves the
function.
ENDFUNCTION without producing the value promised by its
interface.
Local Variables and the Return Boundary
A function may use local variables while calculating its result. These variables belong to the current function call and are not accessed directly by the main program.
FUNCTION CalculateArea(Width : REAL,
Height : REAL) RETURNS REAL
DECLARE Area : REAL
Area β Width * Height
RETURN Area
ENDFUNCTION
PanelArea β CalculateArea(7.5, 4.2)
| Identifier | Location | Role |
|---|---|---|
Width |
Inside the function call | Receives the first argument |
Height |
Inside the function call | Receives the second argument |
Area |
Inside the function | Stores the calculated local result |
PanelArea |
Calling program | Receives the returned value |
A global variable has wider availability. Using global data unnecessarily can make a function harder to test because its result may depend on state that is not visible in its interface.
Area directly. It receives the value through
RETURN Area.
When Is a Function Appropriate?
| Task | Function appropriate? | Reason |
|---|---|---|
| Calculate an area from two dimensions | Yes | The caller needs the calculated numeric result |
| Test whether a reading lies within a permitted range | Yes | A Boolean result can be used in a condition |
| Create a status label from a score | Yes | The function derives one string value |
| Find the largest of several supplied values | Yes | The function produces one selected value |
| Display a menu containing several output statements | Usually a procedure | The purpose is to perform an action rather than produce a value |
| Update several caller variables | Usually a procedure | The task does not naturally produce one direct result |
Useful design question
Using Functions Efficiently
Do not repeat the same function call when its result can be stored and reused.
Repeated calculation
IF CalculateArea(Width, Height) > 50
THEN
OUTPUT "Large area: ", CalculateArea(Width, Height)
ENDIF
The function may calculate the same area twice.
Improved version
Area β CalculateArea(Width, Height)
IF Area > 50
THEN
OUTPUT "Large area: ", Area
ENDIF
Keep dependencies visible
Hidden dependency
FUNCTION CalculateCharge() RETURNS REAL
RETURN GlobalRate * GlobalDuration
ENDFUNCTION
Clearer interface
FUNCTION CalculateCharge(Rate : REAL,
Duration : REAL) RETURNS REAL
RETURN Rate * Duration
ENDFUNCTION
Supplying the values through the interface makes the function easier to test with different data.
A Reliable Method for Tracing a Function
- Locate the function call inside the callerβs expression.
- Record the arguments supplied by the caller.
- Match each argument with the corresponding parameter.
- Enter the function and initialise its local state.
- Execute the body in order, including any selection or repetition.
- Identify the executed
RETURNstatement. - Replace the original call with the returned value.
- Finish evaluating the callerβs expression.
- Continue with the next caller statement.
Suggested trace-table columns
| Stage | Caller expression | Parameters | Local variables | Returned value | Caller result |
|---|---|---|---|---|---|
| 1 | Record the expression containing the call | Record received argument values | Record function calculations | Record the selected return value | Complete the expression |
RETURN. Show how the caller uses the
returned value.
Worked Example: Estimating Drone Endurance
A monitoring drone stores its battery capacity in watt-hours and its average power use in watts. One function calculates the estimated flight time, and a second function creates an endurance label.
Function definitions
FUNCTION CalculateFlightMinutes(CapacityWh : REAL,
AveragePowerW : REAL)
RETURNS REAL
DECLARE Hours : REAL
DECLARE Minutes : REAL
Hours β CapacityWh / AveragePowerW
Minutes β Hours * 60
RETURN Minutes
ENDFUNCTION
FUNCTION GetEnduranceBand(Minutes : REAL)
RETURNS STRING
IF Minutes < 15
THEN
RETURN "Short"
ELSE
IF Minutes <= 30
THEN
RETURN "Standard"
ELSE
RETURN "Extended"
ENDIF
ENDIF
ENDFUNCTION
Main program
DECLARE CapacityWh : REAL
DECLARE AveragePowerW : REAL
DECLARE FlightMinutes : REAL
DECLARE EnduranceBand : STRING
CapacityWh β 72
AveragePowerW β 180
FlightMinutes β CalculateFlightMinutes(
CapacityWh,
AveragePowerW
)
EnduranceBand β GetEnduranceBand(FlightMinutes)
OUTPUT "Estimated flight time: ", FlightMinutes
OUTPUT "Endurance band: ", EnduranceBand
Trace the first function
| Stage | Result |
|---|---|
| Arguments | 72 and 180 |
| Parameters |
CapacityWh = 72,
AveragePowerW = 180
|
| Hours | 72 / 180 = 0.4 |
| Minutes | 0.4 * 60 = 24 |
| Returned value | 24 |
| Caller assignment | FlightMinutes β 24 |
Trace the second function
| Test | Result | Action |
|---|---|---|
24 < 15 |
FALSE |
Continue to the nested condition |
24 <= 30 |
TRUE |
Return "Standard" |
| Caller assignment |
EnduranceBand β "Standard"
|
|
Final output
Estimated flight time: 24
Endurance band: Standard
Interactive: Function Return Visualiser
Choose a scenario and trace the call, local processing, return statement and completed caller expression.
Common Mistakes and Misconceptions
- Writing a function with no returned value: every reachable path should produce a result of the declared type.
-
Using
CALLwith a function: function calls belong within expressions. - Confusing RETURN and OUTPUT: one sends a value to the caller; the other displays data.
- Omitting the return type: a function header must state the type of value produced.
- Returning the wrong type: the returned value must match the declared return type.
- Using a procedure inside an expression: a procedure does not directly produce a replacement value.
- Trying to access a local variable from the caller: the function must return the required value.
- Placing necessary statements after RETURN: they will not execute on that path.
-
Failing to return from one branch: a possible path may
reach
ENDFUNCTIONwithout a result. - Evaluating the caller before the function: the call must be completed before the containing expression can finish.
- Calling the same calculation repeatedly: store the result when it will be reused.
- Depending unnecessarily on global variables: hidden dependencies make testing and tracing more difficult.
Practice
Question 1: identify the parts
FUNCTION GetLimit() RETURNS INTEGER
RETURN 50
ENDFUNCTION
Identify the function header, function name, return type, return statement and end marker.
Question 2: write a simple function
Write a function called GetStartCode that returns the
character 'S'.
Question 3: use a function call
Show how GetStartCode() could be used in an assignment to
CurrentCode.
Question 4: trace replacement
FUNCTION GetIncrease() RETURNS INTEGER
RETURN 7
ENDFUNCTION
Result β 18 + GetIncrease()
Show the expression after replacement and state the final value of
Result.
Question 5: function with parameters
Write a function called CalculatePerimeter that receives two
integer dimensions and returns the perimeter of the rectangle.
Question 6: Boolean function
Write a function called IsValidPercentage that receives an
integer and returns true only when it lies from 0 to 100 inclusive.
Question 7: procedure or function?
Choose and justify the more suitable subroutine:
- Display a five-line menu.
- Calculate the mean of two supplied numbers.
- Test whether a character is uppercase.
- Print a report heading and divider.
Question 8: find the type error
FUNCTION GetQuantity() RETURNS INTEGER
RETURN "Twelve"
ENDFUNCTION
Explain and correct the error.
Question 9: find the unreachable statement
FUNCTION GetMessage() RETURNS STRING
RETURN "Ready"
OUTPUT "Function complete"
ENDFUNCTION
Explain why the output statement cannot execute.
Question 10: complete every return path
FUNCTION GetResult(Passed : BOOLEAN) RETURNS STRING
IF Passed = TRUE
THEN
RETURN "Pass"
ENDIF
ENDFUNCTION
Identify the missing path and rewrite the function.
Question 11: remove repeated calls
IF CalculateVolume(Length, Width, Height) > 100
THEN
OUTPUT CalculateVolume(Length, Width, Height)
ENDIF
Rewrite the code so that the function is called once.
Question 12: nested function call
AreaCategory β GetAreaCategory(
CalculateArea(8, 6)
)
State which function call must be evaluated first and explain why.
Show suggested answers
Question 1
-
Header:
FUNCTION GetLimit() RETURNS INTEGER - Name:
GetLimit - Return type:
INTEGER - Return statement:
RETURN 50 - End marker:
ENDFUNCTION
Question 2
FUNCTION GetStartCode() RETURNS CHAR
RETURN 'S'
ENDFUNCTION
Question 3
CurrentCode β GetStartCode()
Question 4
Result β 18 + 7
Result β 25
Question 5
FUNCTION CalculatePerimeter(Length : INTEGER,
Width : INTEGER)
RETURNS INTEGER
RETURN 2 * (Length + Width)
ENDFUNCTION
Question 6
FUNCTION IsValidPercentage(Value : INTEGER)
RETURNS BOOLEAN
RETURN Value >= 0 AND Value <= 100
ENDFUNCTION
Question 7
- Procedure: the task displays several lines but does not need to produce a value for an expression.
- Function: the caller needs the calculated mean.
- Function: it can return a Boolean result for use in a condition.
- Procedure: its purpose is to perform output actions.
Question 8
The function promises an integer but returns a string. One correction is:
FUNCTION GetQuantity() RETURNS INTEGER
RETURN 12
ENDFUNCTION
Question 9
Executing RETURN "Ready" ends the function call immediately,
so the later output statement is unreachable.
Question 10
FUNCTION GetResult(Passed : BOOLEAN) RETURNS STRING
IF Passed = TRUE
THEN
RETURN "Pass"
ELSE
RETURN "Not passed"
ENDIF
ENDFUNCTION
Question 11
Volume β CalculateVolume(Length, Width, Height)
IF Volume > 100
THEN
OUTPUT Volume
ENDIF
Question 12
CalculateArea(8, 6) is evaluated first because its returned
value becomes the argument supplied to GetAreaCategory.
Review
| Concept | Key idea |
|---|---|
| Function | A named subroutine that returns one value |
| Function header | Identifies the name, parameters and return type |
| Function interface | Describes how the caller supplies data and receives a result |
| Return type | The declared data type of the result |
| Return statement | Sends a value to the caller and ends the function call |
| Function call | Appears within an expression without the keyword CALL |
| Return replacement | The returned value replaces the call before evaluation continues |
| Local variable | Exists only within the subroutine where it is declared |
| Appropriate use | The caller requires one calculated, selected or tested value |