The Return Statement

Functions with No Return Value

A return with no value may be used only in a function that has a return type of void. Functions that return void are not required to contain a return statement. In a void function, an implicit return takes place after the function's final statement.

Functions that Return a Value

Every return in a function with a return type other than void must return a value. The value returned must have the same type as the function return type, or must have a type that can be implicitly converted to that type.

One exception is the main function. The main function is allowed to terminate without a return.

Returning a Nonreference Type

The value returned by a function is used to initialize a temporary object created at the point at which the call was made. A temporary object is an unnamed object created by the compiler when it needs a place to store a result from evaluating an expression.

Example
This function either returns a copy of its parameter named word or it returns an unnamed temporary string that results from adding word and ending. In either case, the return copies that string to the call site.

// return plural version of word if ctr isn't 1
     string make_plural(size_t ctr, const string &word,
                                    const string &ending)
     {
         return (ctr == 1) ? word : word + ending;
     }

Returning a Reference

When a function returns a reference type, the return value is not copied. Instead, the object itself is returned.

Example
Function that returns a reference to the shorter of its two string parameters.

// find longer of two strings
     const string &shorterString(const string &s1, const string &s2)
     {
         return s1.size() < s2.size() ? s1 : s2;
     }

Warning: Never return a reference to a local variable.

Reference Returns Are Lvalues

A function that returns a reference returns an lvalue. That function, therefore, can be used wherever an lvalue is required.

Example

char &get_val(string &str, string::size_type ix)
     {
         return str[ix];
     }
     int main()
     {
         string s("a value");
         cout << s << endl;   // prints a value
         get_val(s, 0) = 'A'; // changes s[0] to A
 
         cout << s << endl;   // prints A value
         return 0;
     }

Recursion

A function that calls itself, either directly or indirectly, is a recursive function.
A recursive function must always define a stopping condition.
The main function may not call itself.

Example
Factorial

// calculate val!, which is 1*2 *3 ... * val
int factorial(int val)
{
         if (val > 1)
             return factorial(val-1) * val;
          return 1;
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.