C++ Return Statement Explained

In C++, the return statement is used to exit a function and pass a value back to the caller. When the function reaches the return statement, it immediately exits the function and returns the specified value. The general form of the return statement is as follows:

return expression;

In the function, the expression is the value to be returned. If the return type of the function is void, the return statement can be omitted, or return; can be used to end the function execution.

For example, the following function will return the sum of two integers:

int add(int a, int b) {
    return a + b;
}

When calling this function, the result will be passed back to the caller.

int result = add(3, 4);
cout << result; // 输出7
bannerAds