return statement

From cppreference.com
 
 
C++ language
General topics
Preprocessor
Comments
Keywords
ASCII chart
Escape sequences
History of C++
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)
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

[edit] Syntax

return expression (1)
return (2)

[edit] Explanation

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

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

[edit] Keywords

return

[edit] 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