C++ return keyword

ww‮tfigi.w‬idea.com

In C++, the return keyword is used to exit a function and return a value to the caller. When the return keyword is executed, the function stops executing and control is returned to the caller. The returned value, if any, is passed back to the caller.

Here's an example function that uses the return keyword to return a value:

int add(int x, int y) {
    int sum = x + y;
    return sum;
}

In this example, the add function takes two integer arguments x and y and returns their sum as an integer. The return keyword is used to exit the function and pass back the value of sum to the caller.

It's important to note that not all functions need to return a value. If a function doesn't have a return statement or if it simply says return;, it will exit the function without returning a value. Here's an example:

void printMessage() {
    std::cout << "Hello, world!" << std::endl;
    return; // optional, since the function doesn't return a value
}

In this example, the printMessage function simply prints a message to the console and exits without returning a value.