Summary: The return keyword ends a function and can return one value.
Most C functions return a value. This is done with the return statement, which also ends the function. The VOLUME.C program from Chapter 1, “Anatomy of a C Program,” (see Figure 2.1) contains such a statement. In that program, the sphere function returns the value of the variable result as follows:
return result;
The following statement in the main function of VOLUME.C calls the sphere function and assigns its return value to the variable volume:
volume = sphere( radius );
Figure 2.6 shows the flow of control as the sphere function returns a value in VOLUME.C.
A return statement can only return a single value. If a function needs to return multiple values, the normal method is to use pointers—a major topic that we'll discuss in Chapter 8, “Pointers.”
NOTE:
In QuickPascal, a function returns a value and a procedure does not. The same distinction applies to QuickBasic FUNCTION and SUB procedures, respectively. In the C language, a function can do both. It can return a value or return nothing.
A function can contain more than one return statement, as shown below:
if( error == 0 )
return 0;
else
return 1;
The code returns a different value in different cases. It returns the value 0 when the variable error is 0 and the value 1 when error is nonzero. (In C, the if and else statements work much like those in other languages. For an explanation, see “The if Statement” and “The else Clause”.)
Summary: A return statement can appear anywhere and need not return a value.
You can place the return keyword anywhere within a function, and the statement need not necessarily return a value. In the following fragment, the naked return statement simply ends the function if the value of count exceeds 500:
if( count > 500 )
return;
else
/* execute more statements... */
A return statement ends the function immediately, no matter where it appears. In the function shown below, the statements following the return never execute:
void do_nothing( void )
{
return;
/* The following statements do not execute */
printf( "This function " );
printf( "prints nothing.\n" );
}
If a function doesn't return a value, and you want the function to end by falling off its closing brace, no return statement is needed. This method is used to end the beep function in BEEPER.C, discussed earlier in this chapter:
void beep( void )
{
printf( "Beep!\n" );
}
You could add a return to the end of this function, but it's not necessary. The function ends automatically.