Information Technology Reference
In-Depth Information
The Return Statement and Void Methods
In the previous section, you saw that methods that return a value must contain return state-
ments. Void methods do not require return statements. When the flow-of-control reaches the
closing curly brace of the method body, control returns to the calling code. No value is inserted
back into the calling code.
Often, however, you can simplify your program logic by exiting the method early, when
certain conditions apply.
￿
You can exit from a method at any time by using the following form of the return state-
ment, with no parameters:
return;
This form of the return statement can be used only with methods declared void .
￿
For example, the following code shows the declaration of a void method called SomeMethod ,
which has three possible places it might return to the calling code. The first two places are in
branches called if statements, which are covered in Chapter 9. The last place is the end of the
method body.
Void return type
void SomeMethod()
{
...
if( SomeCondition ) // If ...
return; // return to the calling code.
...
if( OtherCondition ) // If ...
return; // return to the calling code.
...
} // Return to the calling code.
Search WWH ::




Custom Search