If a function is defined as having a
return type of void, it should not return a value.
In C++, a function which is defined as having a return
type of void, or is a constructor or destructor, must not return a value.
If a function is defined as having a
return type other than void, it should return a value.
A function defined with a return type must include an expression containing the
value to be returned.
When a function returns a value, the value is returned via a return statement to the caller of the function, after being implicitly converted to the return type of the function in which it is defined. 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.
Each time a function is called, new copies of its variables with
automatic storage are created. Because the storage for these automatic
variables may be reused after the function has terminated, a pointer or reference to an automatic 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.
Related information