C++ Function Return Values
The void keyword means a function does not return a value. But often you want a function to compute something and hand the result back to the caller. To do that, you replace void with a data type such as int, double, or string, and use the return statement to send a value back.
Returning a value
The return type at the front of the function tells C++ what kind of value the function gives back. Inside the body, the return statement provides the actual value and immediately ends the function. Whatever value you return can be stored in a variable or used directly in an expression.
A function that returns an int
#include <iostream>
using namespace std;
int add(int x, int y) {
return x + y;
}
int main() {
int result = add(5, 3);
cout << "Sum: " << result << "\n";
cout << "Direct: " << add(10, 20) << "\n";
return 0;
}
// Outputs:
// Sum: 8
// Direct: 30Using the returned value
Because a function call that returns a value behaves like the value itself, you can use it anywhere a value is allowed: assign it to a variable, print it, compare it in an if statement, or even pass it as an argument to another function.
Returning a double and reusing it
#include <iostream>
using namespace std;
double average(double a, double b) {
return (a + b) / 2;
}
int main() {
double avg = average(8.0, 6.0);
if (avg >= 5.0) {
cout << "Average " << avg << " is a pass.\n";
}
return 0;
}
// Outputs: Average 7 is a pass.return also ends the function
As soon as a return statement runs, the function stops and control goes back to the caller. Any code written after that return will not run. This is useful for stopping early, such as returning a result the moment you find it.
Returning early
#include <iostream>
using namespace std;
string checkNumber(int n) {
if (n > 0) {
return "positive";
}
if (n < 0) {
return "negative";
}
return "zero";
}
int main() {
cout << checkNumber(7) << "\n";
cout << checkNumber(-3) << "\n";
cout << checkNumber(0) << "\n";
return 0;
}
// Outputs:
// positive
// negative
// zero