Return Values
Parameters bring values into a function. A return statement sends one value back out, to the code that called it.
#include <iostream>
using namespace std;
int add(int a, int b) {
return a + b;
}
int main() {
int total = add(3, 4);
cout << total << "\n";
return 0;
}
Output:
7
Two things are new here. The return type is int instead of void. It says that this function gives back a whole number. And return a + b; works out the value and sends it back to the caller.
So add(3, 4) has a value, 7, and the line int total = add(3, 4); stores it in total.
A call is a value
You can use a call anywhere you could write a plain number. You can print it directly, pass it to another call, or use it in a calculation:
#include <iostream>
using namespace std;
int add(int a, int b) {
return a + b;
}
int main() {
cout << add(10, 5) << "\n";
cout << add(add(1, 2), 3) << "\n";
cout << add(1, 2) * 10 << "\n";
return 0;
}
Output:
15
6
30
In the second line, the inner call add(1, 2) runs first and gives 3. Then add(3, 3) gives 6.
return ends the function
When return runs, the function stops right there. Any code after it is skipped. So a function can have more than one return, usually inside an if:
#include <iostream>
using namespace std;
int larger(int a, int b) {
if (a > b) {
return a;
}
return b;
}
int main() {
cout << larger(8, 3) << "\n";
cout << larger(2, 9) << "\n";
return 0;
}
Output:
8
9
For larger(8, 3), the if is true, so the function returns 8 and never reaches return b;. For larger(2, 9), the if is false, so it goes on and returns 9.
Make sure every path through the function reaches a return. If you delete the line return b;, this program still compiles without any error. But when a is not larger, the function reaches its end with no value to give back, and C++ does not say what happens then. With the compiler used here, the program printed 8 for the first call and then crashed on the second one.
Now you can also read return 0; at the end of main. main is a function with the return type int, and the 0 it returns tells the computer that the program finished without problems.
In the exercise, complete a function that returns the square of a number.