Table of Contents
A function can return a value to the code that called it. The return type specified in the function declaration or definition determines the type of value that the function can return.
The return statement terminates the execution of the current function and optionally provides a value to the caller. The returned value can be stored in a variable, used directly in an expression, or passed to another function.
Source Code #
#include <iostream>
int multiply(int first, int second)
{
return first * second;
}
int main()
{
int result = multiply(6, 7);
std::cout << "Result: " << result << '\n';
return 0;
}
Output #
Result: 42
Explanation #
int multiply(int first, int second)defines a function that returns anintvalue.return first * second;calculates the product and returns the resulting value to the caller.- The
returnstatement terminates the execution ofmultiply(). multiply(6, 7)calls the function with6and7as arguments.- The value returned by
multiply()is assigned to the variableresult. - A returned value can be used directly in an expression instead of being stored in a variable.
- The type of the returned expression must be compatible with the function’s declared return type.
- A function whose return type is not
voidmust return a value through an appropriatereturnstatement. return 0;inmain()terminates the program successfully.