A value must be returned from a function unless the function
has a return type of void. The return value is specified in a
return statement. The following code fragment shows a function
definition, including the return statement:
int add(int i, int j) { return i + j; // return statement }
The function add() can be called as shown in the following
code fragment:
int a = 10, b = 20; int answer = add(a, b); // answer is 30
In this example, the return statement initializes a variable of the returned type. The variable answer is initialized with the int value 30. The type of the returned expression is checked against the returned type. All standard and user-defined conversions are performed as necessary.
The following return statements show different ways of
returning values to a caller:
return; // Returns no value return result; // Returns the value of result return 1; // Returns the value 1 return (x * x); // Returns the value of x * x
Other than main(), if a function that does not have type void returns without a value (as in the first return statement shown in the example above) the result returned is undefined. In C++, the compiler issues an error message as well.
If main has a return type of int, and does not contain a return expression, it returns the value zero.
Each time a function is called, new copies of its local variables are created. Because the storage for a local variable may be reused after the function has terminated, a pointer to a local variable or a reference to a local variable should not be returned.
If a class object is returned , a temporary object may be created if the class has copy constructors or a destructor.
References can also be used as return types for functions . The reference returns the lvalue of the object to which it refers. This allows you to place function calls on the left side of assignment statements. Referenced return values are used when assignment operators and subscripting operators are overloaded so that the results of the overloaded operators can be used as actual values.
Note: Returning a reference to an automatic variable gives unpredictable results.
Calling Functions and Passing
Arguments
Temporary Objects
Special Overloaded Operators