"Return good for good; return evil with justice" Confucius
The return keyword is used to terminate a function that is expected to give a value when is called.
This means if the function does not return a value (its data type is void), we don’t need to use the return keyword.
On the right side of this return keyword we put the value we want to be returned.
Example:
#include <iostream>
using namespace std;
int multiply (int v1, int v2);
int main(){
int res = multiply (10 , 30);
cout<<res;
return 0;
}
int multiply(int v1 , int v2){
return v1* v2;
}
Output: 300
In the example above, we have the multiply() function which accept 2 arguments, multiply them together and return the result when we call it.
As you can see within the body of multiply() function, we used the return keyword and on the right side of it, we put the expression of v1* v2 which first will resolve and then the result of this expression is the value that will be returned to the caller function.
After the return statement is executed in the multiply() function, the call will return to the caller function (which in this case is the main() function) right where the called to the multiply() function happened and the computer (CPU) will keep executing the rest of instructions in this function.
The call to the multiply() function happened where we wanted to initialized the res variable with a value. So the retuned value of this function will be assigned to the res variable.
Also within the body of the main() function the last line is the return 0; statement.
This will cause the `main()` function to terminate and return to its caller which is the Operating System. (This is equal to the end of the program)
Basically it’s the Operating System that calls the main() function which is the entry point of any C++ programs. So after the return keyword in this function executed, the function is terminated at that point (as well as the program) and any value on the right side of this keyword will be sent to the OS.