Functions, parameters, and return values
A function names one task so the program can call it with data and receive a result.
Learning objectives
- Define and call a value-returning function.
- Distinguish parameters from arguments.
- Describe a function’s input/output contract.
Prerequisites: variables, basic expressions, and main. You should be able to identify a value and a statement before studying function calls.
One task, one name
Complete C++17 program
#include <iostream>
int add(int left, int right) {
return left + right;
}
int main() {
int total = add(4, 6);
std::cout << total << '\n';
}Expected output
10
left and right are parameters in the function definition. The values 4 and 6 are arguments at this call. The expression left + right is evaluated, then return sends the result to the caller.
Trace
The call creates parameter values 4 and 6. The function computes 10 and finishes. The initialization stores 10 in total. The function’s return type, int, tells callers what kind of result to expect.
Common mistakes and applications
- Do not declare an
intfunction without returning aninton every reachable path. - Choose names that reveal the contract;
addis clearer thandoThing. - Functions isolate conversion, validation, calculations, and formatting so each can be tested separately.
Practice
- In
int area(int width, int height), identify the parameters. - What does
return width * height;send to the caller? - Why is a function with a non-void return type expected to return a value on every reachable path?
Show reasoned answers
widthandheight.- The product of the two parameter values.
- The caller expects a result of the declared return type; reaching the end without returning a value from an ordinary value-returning function leads to undefined behavior.