Defining and Calling Functions
What a function actually is
A function is a block of code that is given a name and performs a specific task. You define it once, then call it as many times as you want. Each time you call it, the code inside it runs from top to bottom.
You’ve already been using one function without necessarily thinking of it that way: main. Every C++ program has exactly one main function, and it’s the one the program starts running from. Everything else you write is, in some sense, in service of what main needs to get done.
The parts of a function definition
Here’s a function that calculates pay based on the hours worked and an hourly rate:
double calculatePay(double hoursWorked, double hourlyRate) { double pay = hoursWorked * hourlyRate; return pay;}Here’s what each part is doing:
calculatePayis the name of the function.(double hoursWorked, double hourlyRate)is the parameter list. This function needs these two pieces of information to do its job.- The
{ }block is the body: the actual code that runs when you call the function. - A function needs to be called from another part of the code, and it’s expected to return a value to whoever called it. Here:
double(the one before the function’s name) is the return type. It tells the compiler what kind of value this function will hand back when it finishes.- The return statement (
return pay;) sends a value back to whoever called the function, and exits the function on the spot.
Calling a function
A function won’t run by itself. It needs to be explicitly called:
Here, a function is defined on lines 3-6. It’s called twice inside main, on lines 9 and 12.
Execution starts with main. On reaching the call calculatePay(32.5, 18.50) on line 9, execution jumps into the function, and the two values are handed to its parameters:
hoursWorkedis set to32.5andhourlyRateis set to18.50.- The body runs, computing
pay. - The return statement causes the execution to jump right back to line 9, carrying the returned value with it.
- That value gets stored in
weeklyPay, and the execution carries on to the next line. - The second call, on line 12, runs through the exact same steps, this time computing the overtime.
In general, the values you pass to a function, like 32.5 and 18.50 here, are called arguments. They’re assigned to a function’s parameters in the order in which they’re listed.
Functions that don’t return anything
Not every function needs to return a value. Some are there just to perform an action, like printing a message. For these, you use void as the return type:
void printPayslip(double pay) { std::cout << "Pay for this period: $" << pay << "\n"; std::cout << "Thank you for your work.\n";}void literally means “nothing.” A void function can still use a bare return; with no value specified, if you need to exit early.
A special case: every non-
voidfunction must explicitly return a matching value, with one exception: themainfunction. If execution of main reaches its closing}without hitting a return statement, the compiler insertsreturn 0;automatically.
C++ reads from top to bottom
C++ needs to know a function exists before it is called. This code won’t compile:
int main() { double pay = calculatePay(40.0, 15.00); // error: not known yet}double calculatePay(double hoursWorked, double hourlyRate) { return hoursWorked * hourlyRate;}There are two ways to fix this:
- Simply move the definition of
calculatePayabovemain, as shown earlier in this lesson. - Or, declare it above
mainfirst, with just its signature and no body, like this one:
double calculatePay(double hoursWorked, double hourlyRate);Then define the full function wherever convenient. This is more suitable for advaned projects where the function is called in a different file than the one where it’s defined.
Watching out for mismatched types
The following function call correctly returns 601.25, but this value would truncate if stored in an int:
int pay = calculatePay(32.5, 18.50); // int can't hold the decimal partA similar truncation can take place when passing floating-point values to an int type parameter. Just something to keep in mind.
Checkpoint
Given this code, what happens?
void logEvent(std::string message) {
std::cout << message << "\n";
}
int main() {
int code = logEvent("Server started");
}What does this function print:
int tripleQuantity(int quantity) {
return quantity * 3;
}
int main() {
std::cout << tripleQuantity(1.1);
}Why does this code fail to compile?
int main() {
int area = computeArea(5, 5);
}
int computeArea(int width, int height);
int computeArea(int width, int height) {
return width * height;
}