A function has the derived type "function returning type".
The type can be any data type except array types or
function types, although pointers to arrays and functions can be
returned. If the function returns no value, its type is "function
returning void
", sometimes called a void
function. A void function in C is equivalent to a procedure
in Pascal or a subroutine in FORTRAN. A non-void function in C is
equivalent to a function in these other languages.
Functions can be introduced into a program in one of two ways:
power
is a function returning
int
:
int power(int base, int exp) { int n=1; if (exp < 0) { printf ("Error: Cannot handle negative exponent\n"); return -1; } for ( ; exp; exp--) n = base * n; return n; }
See Section 5.3 for more information on function definitions.
main
declares and calls the function
power
; the definition of the function, where the
code is defined, exists elsewhere:
main() { int power(int base, int exp); /* function declaration */ int x, n, y; . . . y = power(x,n); /* function call */ }
This style of function declaration, in which the parameters are declared in a parameter type list, is called a function prototype. Function prototypes require the compiler to check function arguments for consistency with their parameters, and to convert arguments to the declared types of the parameters.
See Sections 5.4 and 5.5 for more information on function declarations and prototypes.