5.11 The return Statement

The return statement terminates the execution of a function and returns control to the calling function. Execution resumes in the calling function at the point immediately following the call. A return statement can also return a value to the calling function. For more information see “Return Type”.

Syntax

jump-statement : return expression opt ;

The value of expression, if present, is returned to the calling function. If expression is omitted, the return value of the function is undefined. The expression, if present, is converted to the type returned by the function. If the function was declared with return type void, a return statement containing an expression is not legal.

If no return statement appears in a function definition, control automatically returns to the calling function after the last statement of the called function is executed. In this case, the return value of the called function is undefined. If a return value is not required, declare the function to have void return type; otherwise the default return type is int.

Many programmers use parentheses to enclose the expression argument of the return statement. However, C does not require the parentheses.

This example demonstrates the return statement:

void draw( int I, long L );

long sq( int s );

int main()

{

long y;

int x;

y = sq( x );

draw( x, y );

return();

}

long sq( int s )

{

return ( s * s );

}

void draw( int I, long L )

{

/* Statements defining the draw function here */

return;

}

In this example, the main function calls two functions: sq and draw. The sq function returns the value of x * x to main, where the return value is assigned to y. The draw function is declared as a void function and does not return a value. An attempt to assign the return value of draw would cause a diagnostic message to be issued.