------------------------------------------------------------------------------
MC logo
Functional Average III
[^] Code Examples
------------------------------------------------------------------------------
<<Functional Average II average4.c C++ Functions>>
#include <stdio.h>

void print_it(int n1, int n2, int n3, double av);
double av(int a, int b, int);

int main(void)
{
        int n1, n2, n3;

        printf("Enter: ");
        scanf("%d %d %d", &n1, &n2, &n3);

        print_it(n1, n2, n3, av(n1, n2, n3));
}

void print_it(int n1, int n2, int n3, double av)
{
        printf("Mean %d %d %d is %f\n",
                n1, n2, n3, av);
}

double av(int n1, int n2, int n3)
{
        double sum;

        sum = n1 + n2 + n3;
        return sum / 3.0;
}

The line

void print_it(int n1, int n2, int n3, double av);

is called a prototype. It is used when the call will precede the function itself in the program. Java doesn't worry much about the relative location of the definition of a method and its use. Just as variables, functions need to be defined before they are used.

Note that the parameter names given in the prototype are ignored by the compiler. They need not agree with those used in the function itself, and may be omitted entirely. Only the type and number must be the same.

If the prototype is omitted in C++, it is straightforward error. If you omit one in C, the situation is a bit more complicated. The result can be compiler messages which are less than helpful. The reasons are historical, and form a long story.

Reading: pp. 125-144 exc. arrays
<<Functional Average II C++ Functions>>