A function is a sequence of program instructions that performs a specific task, packaged as a unit. This unit can then be used in programs wherever that particular task should be performed. C makes the use of functions easy, convenient and efficient; you will often see a short function defined and called only once, just because it clarifies some piece of code. We have already seen a number of functions including printf, putchar, getchar and main.
A function definition has this form:
return-type function-name(parameter declarations, if any) { declarations statements }
Function definitions can appear in any order, and in one source file or several, although no function can be split between files.
Let’s look at the following program which prints factorials of numbers from 0-9.
#include <stdio.h> #define UPPER 10 int factorial(int); main() { int i; for (i = 0; i < UPPER; i++) { printf("Factorial of %d = %d\n", i, factorial(i)); } return 0; } int factorial(int n) { int result = 1; for(; n >= 1; n--) result *= n; return result; }
The declaration
int factorial(int);
just before main says that factorial is a function that expects an integer argument and returns an integer. This declaration, which is called function prototype has to agree with the definition and uses of the function factorial.
The first line of the function factorial
int factorial(int n)
declares the parameter type and name, and the type of the result that the function returns. The name used by factorial for its parameters are local to factorial along with result, and are not visible to any other function; other functions can use the same name without any conflict.
The variables named in the parenthesised list in a function definition is usually referred as formal argument or parameter. The value passed while calling the function is referred as actual argument or simply argument.
Inside the factorial function, you could see that the initialisation part of the for loop has been left empty. It’s possible to leave any or all of the parts of a for loop empty.
for(; n >= 1; n--) result *= n;
result *= n is a short hand for result = result * n.
The result computed by the factorial function is returned to main by the return statement.
Any expression may follow return:
return expression;
A function need not return a value; a return statement with no expression causes control to be returned to the caller (similar to reaching the end of the function). The calling function may choose to ignore a value returned by a function.
We added
return 0;
at the end of main (If a return type is not mentioned in a function definition, it defaults to int). Since main is a function, it may return a value to its caller, which is in effect the environment in which the program was executed. Typically, a return value of zero implies normal termination; non-zero values signal unusual or erroneous termination conditions. This was omitted previously for simplicity.