A C++ function is a named block of code that you can run with different inputs and that gives you a result back. Writing your first one takes four pieces, and learning those four pieces is what turns a file of loose statements into a program you can grow.
This is the first lesson in the Functions module, and the next lesson in this module is about "What Is the Difference Between Pass-by-Value and Pass-by-Reference?".
The shape of a function
A C++ function has four parts. There is a return type, there is a name, there is a parameter list, and there is a body.
#include <iostream>
double line_total(double unit_price, int quantity) {
return unit_price * quantity;
}
int main() {
double total = line_total(4.50, 3);
std::cout << "line total: " << total << '\n';
return 0;
}So here is what each part does. The return type double says what kind of value comes back. The name line_total is what you call it by. The parameter list (double unit_price, int quantity) says what it needs. And the body is the work, which here is one multiply and a return.
Return types and the return statement
The return statement gives a value back to the caller and ends the function there. Anything after the return in the same block never runs.
#include <iostream>
int cakes_baked() {
return 24;
}
void announce_order(int order_number) {
std::cout << "order " << order_number << " received\n";
}
int main() {
std::cout << "cakes baked: " << cakes_baked() << '\n';
announce_order(4821);
return 0;
}A function that returns nothing is written as void, and it simply does not have a return statement. The announce_order function above is an example. It prints a line and it ends.
And leaving a return off the end of a non-void function is a compile error in C++, which is a genuine improvement over C.
Parameters and arguments
The names in the parameter list are called parameters. The values you pass in at the call site are called arguments. The function receives the arguments as its parameters.
And that is what makes functions safe to use. Two functions can both have a variable called total without any interference.
#include <iostream>
int main() {
{
int total = 10; // a different variable entirely
std::cout << "inner total: " << total << '\n';
}
int total = 99;
std::cout << "outer total: " << total << '\n';
return 0;
}Local scope and shadowing
Every variable that you declare inside a function is local to that function. It does not exist before the call and it does not exist after the return. The block in the example above is a smaller scope still, because it is inside braces.
And when an inner block declares a name that an outer block already has, the inner one wins for the length of the inner block. That is called shadowing. The compiler warns about it when you compile with -Wall, and it is worth reading the warning.
Calling a function before it is defined
You can call a function that is defined further down the file, but you have to tell the compiler about it first. A forward declaration, also called a prototype, does exactly that.
#include <iostream>
double apply_discount(double total, double percent); // declaration
int main() {
std::cout << "after discount: " << apply_discount(100.0, 10.0) << '\n';
return 0;
}
double apply_discount(double total, double percent) { // definition
return total - total * percent / 100.0;
}The declaration tells the compiler the name, the parameter types and the return type. The definition later on supplies the body. The two have to agree, and the compiler checks that they do.
Functions that call functions
A small function that computes one thing becomes the building block of a larger one.
#include <iostream>
double line_total(double unit_price, int quantity) {
return unit_price * quantity;
}
double subtotal(const double lines[], int count) {
double sum = 0.0;
for (int i = 0; i < count; ++i) {
sum += lines[i];
}
return sum;
}
int main() {
double lines[3] = {13.50, 9.00, 22.50};
double before_tax = subtotal(lines, 3);
std::cout << "subtotal: " << before_tax << '\n';
std::cout << "with tax: " << before_tax * 1.08 << '\n';
return 0;
}And this is where the payoff of small functions appears. Each one does one job, each one can be tested on its own, and the larger one reads like a list of steps.
Returning more than one value
When you need two or three results, the usual approach is to bundle them into a small struct and return that.
#include <iostream>
struct PriceBreakdown {
double subtotal;
double discount;
double total;
};
PriceBreakdown price_order(double subtotal, double percent) {
PriceBreakdown result;
result.subtotal = subtotal;
result.discount = subtotal * percent / 100.0;
result.total = subtotal - result.discount;
return result;
}
int main() {
PriceBreakdown p = price_order(24.00, 15.0);
std::cout << "subtotal: " << p.subtotal << '\n';
std::cout << "discount: " << p.discount << '\n';
std::cout << "total: " << p.total << '\n';
return 0;
}The alternative would be to pass in pointers to output variables, and that works, but it makes the call site harder to read and it is easy to forget one of them.
Documenting a function
A short comment above the function tells the next reader what it does and what it expects.
// Returns the price of one order line after the quantity is applied.
// unit_price: price of a single item in pounds
// quantity: number of items ordered
double line_total(double unit_price, int quantity) {
return unit_price * quantity;
}And there is one thing that is worth knowing. The comment above the declaration in the header is the one that matters, because that is the interface that the other programmers use. The comment above the definition is for the person who has to change the body.
Quick reference
- A function is a return type, a name, a parameter list and a body.
- Parameters are the names in the list, and arguments are the values at the call site.
- A function that returns nothing is declared with
voidand has no return statement. - Leaving a return off the end of a non-void function is a compile error.
- Local variables do not exist outside the function that declares them.
- A forward declaration lets you call a function before its definition.
- Return a small struct when you need more than one value.
Try it yourself: write a function that takes the unit price and the quantity and gives back the line total, then write a second one that takes an array of line totals and gives back the order subtotal. Call them from main in both orders, and confirm that the order of the calls makes no difference to the answers.