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: 30
Note: The type of the value you return must match the function's declared return type. If add() is declared to return int, then return x + y must produce an int.

Using 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
Return typeWhat it returnsExample return statement
voidNothingreturn; (optional)
intA whole numberreturn 42;
doubleA decimal numberreturn 3.14;
booltrue or falsereturn age >= 18;
stringTextreturn "done";
Note: A non-void function should return a value on every path through the code. Forgetting to return from some branch leads to undefined behavior, so make sure every possible route ends in a return statement.