1. Goals
Split a calculation into functions with meaningful names.
Distinguish data passed into a function from its returned result.
Predict which variable changes when an integer is passed by value.
2. Prerequisites
You can declare int variables, add and multiply numbers, use if, and run
main.cpp. Pointers and references are not needed for this lesson.
3. Explanation
Suppose you need to add a fee to an item's price, then calculate the cost of
several items. Putting everything in main makes the purpose of each step
less obvious. addFee and totalPrice give the two operations clear names.
In int addFee(int price), the first int is the result type, addFee is
the function name, and price is a parameter. In the call addFee(120),
120 is the argument: the actual value supplied for that call.
return sends the result back and finishes the function.
An int price parameter holds its own value. If you pass the price variable
from main, adding 5 to the parameter does not change that variable.
To use the new value, save the result: int next = addFee(price);.
This is passing by value; parameter initialization is described in the
C++ working draft on function calls.
The two lines ending in ; at the start of the example are declarations.
They tell the compiler the functions' names, input types, and result types
before the calls in main. The parts with { ... } below are definitions:
they contain the work to perform. Declarations and definitions must agree.
You can also place the complete definitions before main.
Each function has its own scope. total in totalPrice and total in main
are separate variables. A function cannot automatically see the local variables
of its caller; pass the data it needs as arguments. After it finishes, the
returned numeric value can still be used even though its local variable's
lifetime has ended.
An ordinary function returning int needs a result on every path that finishes
normally. main is an exception: reaching the end of its body without an
explicit return is equivalent to return 0;.
A function that only performs an action, such as printing a greeting, can use
void, meaning there is no result value to assign to a variable.
Do not confuse std::cout with return: printing does not provide a result
for the caller's next calculation.
The example uses small prices and quantities. When extending a function, define its input range so multiplication cannot exceed the type's limits. A meaningful function name does not make every integer a valid input.
4. Runnable example
Save this as main.cpp and compile with C++17 as in the first lesson.
The program does not read any input.
#include <iostream>
int addFee(int price);
int totalPrice(int unitPrice, int quantity);
int main() {
int price = 120;
int priceWithFee = addFee(price);
int total = totalPrice(priceWithFee, 3);
std::cout << "Original: " << price << '\n';
std::cout << "With fee: " << priceWithFee << '\n';
std::cout << "Total: " << total << '\n';
return 0;
}
int addFee(int price) {
price += 5;
return price;
}
int totalPrice(int unitPrice, int quantity) {
int total = unitPrice * quantity;
return total;
}Exact output:
Original: 120
With fee: 125
Total: 375Follow the data: 120 enters addFee, and the result 125 is saved in
priceWithFee. Then 125 and 3 enter totalPrice, producing 375.
The original price variable remains 120.
5. Common mistakes
Calling a function before declaring it: the compiler does not know its name.
Declaring a called function without defining it: usually a link-time error.
Writing
addFee(price);and expectingpriceto increase: the result is discarded.Swapping arguments with the same type: it may compile but change the meaning.
Returning only inside one
ifbranch: another path may lack a result.Using a local variable from
mainin another function without passing it in.
6. Practice
Change the original price to
80and quantity to2. Predict the result before running: original80, with fee85, total170.Write
int square(int number)and try0,3, and-4; expect0,9, and16. Keep this exercise's inputs between-100and100.Write
bool canAfford(int total, int budget). Returntruewhen the budget covers the total, including equality. Try a total of100with budgets99,100, and101.Move the definition of
addFeeabovemainand remove its separate declaration. Recompile; the program's behavior should stay the same.
7. Self-check
What is
amountafterint amount = 10; addFee(amount);? Answer:10. The function receives its own value, and the result15is discarded.Why does
int result = totalPrice(20, 4);not require the function's localtotalto live forever? Answer: the numeric value80is returned to initializeresult;resultis not the function's local variable.How does a function declaration differ from a definition? Answer: a declaration introduces how to call it; a definition provides its executable body. A declaration cannot replace a used function's definition.
Sample code
Source file
cpp98_foundation/05_functions/main.cpp
#include <iostream>
int addFee(int price);
int totalPrice(int unitPrice, int quantity);
int main() {
int price = 120;
int priceWithFee = addFee(price);
int total = totalPrice(priceWithFee, 3);
std::cout << "Original: " << price << '\n';
std::cout << "With fee: " << priceWithFee << '\n';
std::cout << "Total: " << total << '\n';
return 0;
}
int addFee(int price) {
price += 5;
return price;
}
int totalPrice(int unitPrice, int quantity) {
int total = unitPrice * quantity;
return total;
}