A function is a named, reusable subprogram that performs a specific task and returns a value. Functions are used to divide a program into manageable parts, reduce repeated code, and make programs easier to understand, test, and maintain.
How a function works
A function is defined once and executed through a function call. It may receive parameters, which are variables listed in its definition, and return a result to the calling statement.
FUNCTION rectangleArea(length, width)
RETURN length * width
END FUNCTION
area = rectangleArea(5, 3)
Here, length and width are parameters. The values 5 and 3 supplied in the function call are arguments. The function calculates the area, returns 15, and that value is assigned to area.
A function normally has a return type, such as integer, Boolean, or string. The returned value can be assigned to a variable, displayed, passed to another function, or used within an expression.
Why functions are used
| Benefit | How it improves a program |
|---|---|
| Decomposition | Breaks a complex problem into smaller, manageable tasks. |
| Reusability | Allows the same code to be called repeatedly without duplication. |
| Abstraction | Hides implementation details so the programmer can focus on what the function does. |
| Maintainability | A correction or update can be made in one function rather than in every repeated section. |
| Testing | Individual functions can be tested separately using known inputs and expected outputs. |
| Readability | Meaningful function names communicate the purpose of different program sections. |
A common misconception is that every named subprogram is a function. In IB terminology, a procedure performs a task but does not return a value, whereas a function returns a value.
IB exam technique
For a question asking you to explain why functions are used, identify a benefit and develop it. For example: functions support reusability because one tested block can be called many times, reducing duplicated code and the likelihood of inconsistent errors. In trace or construction questions, distinguish carefully between parameters, arguments, function calls, and returned values.