return

suggest change

Returns control from a function to its caller.

If return has an operand, the operand is converted to the function’s return type, and the converted value is returned to the caller.

int f() {
    return 42;
}
int x = f(); // x is 42
int g() {
    return 3.14;
}
int y = g(); // y is 3

If return does not have an operand, the function must have void return type. As a special case, a void-returning function can also return an expression if the expression has type void.

#include <cmath>
#include <iostream>

void f(int x) {
    if (x < 0) return;
    std::cout << std::sqrt(x);
}
int g() { return 42; }
void h() {
    return f(1); // calls f, then returns
    return g(); // ill-formed
}

Returning from the initial invocation of main destroys its automatic local variables and then behaves as if std::exit were called with the return value. Calling std::exit directly does not destroy automatic local variables. Reaching the end of main is equivalent to return 0;.

#include <cstdlib>
#include <iostream>

int main(int argc, char** argv) {
    if (argc < 2) {
        std::cout << "Missing argument\n";
        return EXIT_FAILURE; // destroys automatic objects, then calls std::exit(EXIT_FAILURE)
    }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents