Namespaces
Variants
Views
Actions

return statement

From cppreference.com
< cpp‎ | language
Revision as of 09:00, 10 May 2013 by P12 (Talk | contribs)

Terminates current function and returns specified value to the caller function.

Contents

Syntax

Template:sparam(optional) return Template:sparam(optional) ; (1)
Template:sparam(optional) return Template:sparam ; (2) (since C++11)
Template:sparam(C++11) - optional sequence of any number of attributes
Template:sparam - expression, convertible to the function return type
Template:sparam - brace-enclosed list of initializers and other braced-init-lists

Explanation

1) Evaluates the Template:sparam, terminates the current function and returns the result of the Template:sparam to the caller, after implicit conversion to the function return type. The Template:sparam is optional in functions whose return type is (possibly cv-qualified) void, in constructors and in destructors.
2) Uses copy-list-initialization to construct the return value of the function.

Notes

If control reaches the end of a function without encountering a return statement, return; is executed (except in the main function, where return 0; is executed).

Flowing off the end of a value-returning function (except main) without a return statement is undefined behavior.

In a function returning void, the return statement with Template:sparam can be used, if the expression type is void.

Returning by value may involve construction and copy/move of a temporary object, unless copy elision is used.

Keywords

return

Example

#include <iostream>
#include <string>
#include <utility>
 
void fa(int i)
{
    if (i == 2)
         return;
    std::cout << i << '\n';
} // implied return;
 
int fb(int i)
{
    if (i > 4)
         return 4;
    std::cout << i << '\n';
    return 2;
}
 
std::pair<std::string, int> fc(const char* p, int x)
{
    return {p, x};
}
 
void fd()
{
    return fa(10); // fa(10) is a void expression
}
 
int main()
{
    fa(2); // returns, does nothing when i==2
    fa(1); // prints its argument, then returns
    int i = fb(5); // prints its argument, returns 2
    i = fb(i); // prints its argument, returns 4
    std::cout << i << '\n'
              << fc("Hello", 7).second << '\n';;
    fd();
}

Output:

1
4
2
7
10