2.11. Functions¶
Three required pieces of code make up the use of a function in a program are:
- The function prototype.
- The calling of the function.
- The definition of the function.
2.11.1. Function Prototypes¶
The function prototype defines:
- The name of the function.
- The type of value returned by the function.
- The number of arguments passed to the function and the data type of the arguments passed to the function.
Function prototypes are often placed in included files. (file.h)
2.11.2. Function Definition¶
The function definition defines the code used to evaluate the function.
2.11.3. Return statement¶
- The keyword return causes the function to exit, passing control back to the calling function.
- A return is not required if the function is of type void.
- return is the facility for returning a single value to the calling function.
2.11.4. Function Invocation - call-by-value¶
Arguments are passed to a function by value only. The name of the variable in the calling function has no meaning in the called function. Pointers provide a way to enhance what is passed to a function.
2.11.5. Function Example¶
#include <stdio.h> int min( int, int ); /* function prototype */ int main(void) { int val1,val2; printf("Please enter an integer value: "); scanf( "%d", &val1 ); printf("\nPlease enter another integer value: "); scanf( "%d", &val2 ); printf( "\nThe smaller value is %d\n", min( val1, val2 )); return 0; } int min( int x, int y ) /* function definition */ { if( x <= y ) return x; else return y; }
Now complete Homework 4 - Newton’s Square Root Algorithm in a Function.