Function Return Values

You must return a value 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.

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.

C++If a class object is returned, a temporary object may be created if the class has copy constructors or a destructor.

Related References

IBM Copyright 2003