<< Chapter < Page | Chapter >> Page > |
This function has the name cylinderVolume, and has two parameters, r and h, both with type double. It returns a value with the type double.
return statement
The return statement ends execution of the current function, and jumps back to where the function was called:
return [expression];
expression is evaluated and the result is given to the caller as the value of the function call. This return value is converted to the function's return type, if necessary.
A function can contain any number of return statements:
// Return the smaller of two integer arguments.
int min( int a, int b ){
if ( a<b ) return a;
else return b;}
The contents of this function block can also be expressed by the following single statement:
return ( a<b ? a : b );
The parentheses do not affect the behavior of the return statement. However, complex return expressions are often enclosed in parentheses for the sake of readability.
A return statement with no expression can only be used in a function of type void. In fact, such functions do not need to have a return statement at all. If no return statement is encountered in a function, the program flow returns to the caller when the end of the function block is reached.
The instruction to execute a function, the function call, consists of the function's name and the operator ( ). For example, the following statement calls the function maximum to compute the maximum of the matrix mat, which has r rows and c columns:
maximum( r, c, mat );
The program first allocates storage space for the parameters, then copies the argument values to the corresponding locations. Then the program jumps to the beginning of the function, and execution of the function begins with first variable definition or statement in the function block.
If the program reaches a return statement or the closing brace } of the function block, execution of the function ends, and the program jumps back to the calling function. If the program "falls off the end" of the function by reaching the closing brace, the value returned to the caller is undefined. For this reason, you must use a return statement to stop any function that does not have the type void. The value of the return expression is returned to the calling function.
One of the C language’s strengths is its flexibility in defining data storage. There are two aspects that can be controlled in C: scope and lifetime. Scope refers to the places in the code from which the variable can be accessed. Lifetime refers to the points in time at which the variable can be accessed.
Three scopes are available to the programmer:
Notification Switch
Would you like to follow the 'Introduction to computer science' conversation and receive update notifications?