5.1 Functions and Calls
A function gives a name to a reusable block of code. It can receive input values, run statements, and return a result.
cpp
int larger(int a, int b) {
if (a > b) {
return a;
}
return b;
}This function has a return type (int), a name (larger), and two parameters (a and b). A call supplies arguments.
cpp
int best = larger(17, 23);
std::cout << best << std::endl;Functions can also perform an action without returning a useful value. Use void for that case.
cpp
void print_board() {
std::cout << "###" << std::endl;
std::cout << "###" << std::endl;
}C++ executes a function call by pausing the caller, creating space for the called function's parameters and local variables, running the function body, and then returning to the caller.
Loading interactive lab...
Breaking a program into functions makes each part easier to read and test. A distance formula, for example, is easier to reuse when it has its own function.
cpp
#include <cmath>
double distance(double x1, double y1, double x2, double y2) {
double dx = x2 - x1;
double dy = y2 - y1;
return std::sqrt(dx * dx + dy * dy);
}Loading concept check...
Loading concept check...
Loading concept check...
Loading practice...
Loading practice...
Loading practice...
Loading practice...