Namespaces
Variants
Views
Actions

return statement

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

 
 
C++ language
General topics
Flow control
Conditional execution statements
Iteration statements (loops)
Jump statements
goto - return
Functions
Function declaration
Lambda function declaration
inline specifier
Exception specifications (deprecated)
noexcept specifier (C++11)
Exceptions
Namespaces
Types
Specifiers
decltype (C++11)
auto (C++11)
alignas (C++11)
Storage duration specifiers
Initialization
Expressions
Alternative representations
Literals
Boolean - Integer - Floating-point
Character - String - nullptr (C++11)
User-defined (C++11)
Utilities
Attributes (C++11)
Types
typedef declaration
Type alias declaration (C++11)
Casts
Implicit conversions - Explicit conversions
static_cast - dynamic_cast
const_cast - reinterpret_cast
Memory allocation
Classes
Class-specific function properties
Special member functions
Templates
Miscellaneous
 

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