|
|
|
|
|
|
|
Alternatively, there is a second form of the return statement. It looks like this: |
|
|
|
|
|
|
|
|
This statement is valid only for void functions. It can appear anywhere in the body of the function; it causes control to exit the function immediately and return to the caller. Here's an example: |
|
|
|
|
|
|
|
|
void SomeFunc( int n )
{
if (n > 50)
{
cout << The value is out of range.;
return;
}
n = 412 * n;
cout << n;
} |
|
|
|
|
|
|
|
|
In this (nonsense) example, there are two ways for control to exit the function. At function entry, the value of n is tested. If it is greater than 50, the function prints a message and returns immediately without executing any more statements. If n is less than or equal to 50, the If statement's thenclause is skipped and control proceeds to the assignment statement. After the last statement, control returns to the caller. |
|
|
|
|
|
|
|
|
Another way of writing the above function is to use an If-Then-Else structure: |
|
|
|
|
|
|
|
|
void SomeFunc( int n )
{
if (n > 50)
cout << The value is out of range.;
else
{
n = 412 * n;
cout << n;
}
} |
|
|
|
|
|
|
|
|
If you asked different programmers about these two versions of the function, you would get differing opinions. Some prefer the first version, saying that it is most straightforward to use return statements whenever it logically makes sense to do so. Others insist on the single-entry/single-exit approach |
|
|
|
|
|