C++ Return Values

In C++, a return value is the value a function sends back to the part of the program that called it. Functions that return a value must specify a return type other than void and use the return statement to send the result.

Syntax

return_type function_name(parameters) {
    // code
    return value;
}

Where:

  • return_type – Data type of the value to be returned (e.g., int, float, double, string).
  • return value; – The value that will be sent back to the caller.

Example Program: Returning an Integer

#include <iostream>
using namespace std;

// Function that returns an integer
int add(int a, int b) {
    return a + b;
}

int main() {

    int sum = add(10, 20); // Function call
    cout << "Sum: " << sum << endl;

    return 0;
}

Output

Sum: 30

Example: Returning a Floating-Point Value

#include <iostream>
using namespace std;

// Function that returns a double
double multiply(double x, double y) {
    return x * y;
}

int main() {

    double result = multiply(5.5, 2.0);
    cout << "Result: " << result << endl;

    return 0;
}

Output

Result: 11

Important Notes

  • Functions with a return type must use the return statement to return a value.
  • If a function does not return a value, its return type must be void.
  • The returned value can be stored in a variable, used in expressions, or passed to another function.

Next Topic

Next, learn about Function Overloading in C++.