Lesson 91 +10 XP

Function Return Values

Function Return Values

A function doesn't have to just print things - it can produce a return value: a value it hands back to whoever called it.

The return type

The type you write before the function's name is the type of value the function sends back. Here's a function that returns an integer:

int add() {
  return 5;
}
  • The return type is int, so the function promises to send back an int.
  • return 5; is the statement that actually sends 5 back.
  • Every path through the function must return a value of that type.

Using the result

The call to add() acts as a value. You can store it, print it, or use it in math:

int result = add();     // result is now 5
cout << add();          // prints 5
cout << add() + add();  // 5 + 5 = 10

Return happens early

The return statement does two jobs: it gives back the value and it ends the function immediately. Any statements after a return never run.

int sign() {
  return 1;
  cout << "never printed";   // dead code
}

The type must match

The returned value and the declared return type must agree. int add() { return 5; } is fine; trying to return a string from an int function is an error. In some cases C++ converts a value silently to fit the return type (like turning an int into a double).

TL;DR

  • The return type is written before the function name: int add().
  • return x; hands the value back and stops the function.
  • A call is a value: int result = add();.
  • Statements after a return never run.
  • The returned value must match the declared return type.