Table of Contents
The code written in a C program is divided into functions. Although similar to Java “methods”, C functions are not assigned neither to a class nor to an object. A C function is distinguished only by its name. Two functions with the same name but different number and parameter types is considered a multiple definition, and thus, an error.
Functions typically encapsulate an operation more or less complex from which a result is derived. To execute this operations, functions may require invoking other functions (or even themselves like in the case of recursive functions).
The functions in a program are entities that given a set of data (the parameters), they are in charge of performing a very precise task until a result is returned. Ideally, complex tasks need to be divided in simpler portions that are implemented as functions. The division and grouping of tasks into functions is one of the most important aspects in program design.
C Functions have the following format:
result_type NAME(param1_type param1, param2_type param2, ... )
{
/* Function body */
}
When a function is invoked, values are assigned to the
parameters and the body is begins to execute until the end or when the
instruction return
is encountered. If the function returns a
result, this instruction must be followed by the data to return. For
example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | int search(int table[], int size) { int i, j; if (size == 0) { return 0; } j = 0; for (i = 0; i < size; i++) { j += table[i]; } return j; } |
The execution of the function starts in line 4. If the
parameter size
has value zero, the function terminates and
returns the value zero. If not, the loop is executed and the value of
variable j
is returned. The type of the expression following
the instruction return
must be identical to the data type
of the result declared in line 1.
The call to a function is coded by its name followed by a comma-separated list of parameter values in parenthesis. If the function returns a result, the call is replaced by its result in the expression including it. For example.
1 2 3 4 5 6 7 8 9 | int addition(int a, int b)
{
return (a + b);
}
int main()
{
int c;
c = c * addition(12, 32);
} |