return Ends the Function
return does two things at once: it returns a value and ends the function right away. The rest of the function doesn't run:
#include <iostream>
int add(int a, int b) {
return a + b;
std::cout << "This line never runs." << std::endl;
}
int main() {
std::cout << add(2, 3) << std::endl;
return 0;
}This program prints:
5The line after return never runs, because the function already ended one line earlier.
This is especially handy together with conditions. The following function describes the weather by the temperature:
#include <iostream>
#include <string>
std::string describeWeather(int degrees) {
if (degrees < 0) {
return "freezing";
}
if (degrees < 20) {
return "cold";
}
return "warm";
}
int main() {
std::cout << describeWeather(-5) << std::endl;
std::cout << describeWeather(12) << std::endl;
std::cout << describeWeather(25) << std::endl;
return 0;
}This program prints:
freezing
cold
warmLet's go through all three calls:
describeWeather(-5):-5 < 0is true, so the function returns"freezing"and ends. The second condition isn't checked at all.describeWeather(12): the first condition is false and the second is true, so the function returns"cold".describeWeather(25): neither condition is true, so the function gets all the way to the last line and returns"warm".
We didn't need any else: as soon as a return runs, the rest of the function is skipped anyway. (With else if and else, the function would work the same.) But the order of the conditions matters, because the first return that runs wins. If the function checked degrees < 20 first, it would return "cold" for -5, because -5 is less than 20 too.
Watch out for the last return. If you leave it out, the function has nothing to return for 25: no condition is true, and the function reaches its end without a return. The program then prints freezing and cold and stops with an error, below which you see the warning warning: non-void function does not return a value in all control paths. A function that isn't void must always return a value, whichever way the conditions turn out.
In a void function, you can write return; without a value. The function then simply ends:
#include <iostream>
void printDivision(int a, int b) {
if (b == 0) {
std::cout << "You can't divide by zero." << std::endl;
return;
}
std::cout << a / b << std::endl;
}
int main() {
printDivision(10, 2);
printDivision(10, 0);
return 0;
}This program prints:
5
You can't divide by zero.Instructions
The function ticketPrice returns the price of a zoo ticket for a visitor of the given age. So far, it returns 200 for everybody. Above the line return 200;, add conditions: children under 6 get in for free (0), and visitors under 18 pay 100. The program then prints 0, 100 and 200.
Seniors aged 65 and over pay 100 too. Add a condition for them to the function, and at the end of main, before return 0;, print ticketPrice(70). The program prints one more 100.
Start programming for free
7/10