TOPIC 9.2.1
Return
The C++ return statement can be used for more than just returning a value. The return statement can be used to exit the function even when the return type is void. When this is done the function is ended and control is returned to the calling program. Multiple return statements can be used within a function. This could be used to return different values when certain conditions were met. The calling program does not always have to capture the value returned by the function. If the program does not need the data being returned, the data will be lost. The following examples will reinforce the topics described.
This example show the use of multiple return statements within a function.
int questions()
{
char answer;
cout<<"Would you like to return a 1 ?";
cin>>answer;
if(answer == 'Y' || answer == 'y')
return 1;
cout<<"Would you like to return a 2 ?";
cin>>answer;
if(answer == 'Y' || answer == 'y')
return 2;
cout<<"Or would you like to return a 3 ?";
cin>>answer;
if(answer == 'Y' || answer == 'y')
return 3;
}
This example shows that the calling program does not have to use the value returned by the function question().
#include <iostream.h>
main()
{
question();
cout<<"You have no control over me."
cout<<"You selected 2."
return 0;
}