Use of return statements in C++ functions

  • 2020-04-01 21:29:17
  • OfStack

The return statement in C++ is an important statement in a function that terminates the function being executed and returns control to the function that called it.

Return statements come in two forms :
The return;
Return expression;
A function that returns no value
A return statement without a return value can only be used to return functions of type void. A return statement is used to cause a mandatory end of a function, similar to the use of a break statement in a loop structure.
Example:

 
void swap(int &v1,int &v2) 
{ 
if(v1==v2) 
return; 
int temp=v2; 
v2=v1; 
v1=tmp; 
} 

A return function of type void cannot usually use a return statement of the second form, that is, it can return the result of a call to another function whose return type is also void:
 
void do_swap(int &v1,int &v2) 
{int temp=v2; 
v2=v1; 
v1=tmp; 
} 
void swap(int &v1,int &v2) 
{ 
if(v1==v2) 
return false; 
return do_swap(v1,v2) 
} 

2. Functions with return values
Any function whose return type is not void must return a value of the same type as the function or be implicitly converted to the function's return type.

Although C++ cannot guarantee the correctness of the result, it can guarantee that the function returns the result of the appropriate type every time it returns. For example, the following program cannot compile: < img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201212/2012121516581251.jpg ">

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201212/2012121516581252.jpg ">

 

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201212/2012121516581253.jpg ">

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201212/2012121516581254.jpg ">

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201212/2012121516581255.jpg ">

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201212/2012121516581256.jpg ">


Related articles: