return statement

From Cppreference

Jump to: navigation, search

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