Namespaces
Variants
Views
Actions

return statement

From cppreference.com
< cpp‎ | language
Revision as of 20:29, 2 November 2012 by P12bot (Talk | contribs)

 
 
C++ language
General topics
Flow control
Conditional execution statements
Iteration statements
Jump statements
goto statement
return statement
Functions
function declaration
lambda function declaration
function template
inline specifier
exception specifications (deprecated)
noexcept specifier (C++11)
Exceptions
Namespaces
Types
decltype specifier (C++11)
Specifiers
cv specifiers
storage duration specifiers
constexpr specifier (C++11)
auto specifier (C++11)
alignas specifier (C++11)
Initialization
Literals
Expressions
alternative representations
Utilities
Types
typedef declaration
type alias declaration (C++11)
attributes (C++11)
Casts
implicit conversions
const_cast conversion
static_cast conversion
dynamic_cast conversion
reinterpret_cast conversion
C-style and functional cast
Memory allocation
Classes
Class-specific function properties
Special member functions
Templates
class template
function template
template specialization
parameter packs (C++11)
Miscellaneous
Inline assembly
 

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

Contents

Syntax

return Template:sparam (1)
return (2)

Explanation

The first version evaluates the Template:sparam, terminates the current function and returns the result of the Template:sparam to the caller function. The resulting type of the Template:sparam must be convertible to function return type.

The second version terminates the current function. Only valid if the function return type is void.

Keywords

return

Example

#include <iostream>
 
void fa(int i) 
{
    if (i == 2) return;
    std::cout << i << '\n';
}
 
int fb(int i) 
{
    if (i > 4) return 4;
    std::cout << i << '\n';
    return 2;
}
 
int main() 
{
    fa(2);
    fa(1);
    int i = fb(5);
    i = fb(i);
    std::cout << i << '\n';
}

Output:

1
4
2