The return statement has two forms:
1.return;//Return statement without return value
2.return 0;//Return statement with return value, or return a variable or a function.
The return statement without a return value is used to interrupt the execution of a function whose return value is of type void, while the return statement with a return value does not.
After replacing return 0; with return;, the operation is successful:
An extension of return:
1.return;//Return statement without return value
2.return 0;//Return statement with return value, or return a variable or a function.
The return statement without a return value is used to interrupt the execution of a function whose return value is of type void, while the return statement with a return value does not.
Code that uses return expression; fails to compile. The following is the failure code:
#include <iostream> using namespace std; void func(){ cout<<"begin"<<endl; return 0;/*There is a problem here. At this time, the function of return; is equivalent to the function of break; used to interrupt the loop. So it shouldn't return a specific value. */ cout<<"end"<<endl; } int main(){ func(); return 0; }
After replacing return 0; with return;, the operation is successful:
#include <iostream> using namespace std; void func(){ cout<<"begin"<<endl; return; cout<<"end"<<endl; } int main(){ func(); return 0; }Summary: The role of return; is equivalent to the role of break; used to interrupt the loop, while return 0; is another usage of return, dedicated to returning its value from a function whose return value is not void.
An extension of return:
#include <iostream> using namespace std; void func(){ //This function has no return value, so this function should use return. cout<<"begin"<<endl; cout<<"end"<<endl; return;//Return the return value of the function whose return value is void, which can be executed successfully } int main(){ //③The main function has a return value, and the return value type is int, so it can return 0 func(); return 0; }Compiled.