------------------------------------------------------------------------------
MC logo
Functional Average III
[^] CSc 220 Home
------------------------------------------------------------------------------
[Introduction] [Boolean and Control] [Functions] [Arrays and Pointers] [Dynamic Arrays] [Array Errors] [Command Array] [Standard Containers] [Structs and Classes] [Automatic Pointer] [Multi-File Programs] [Copying Objects] [Templates] [Inheritance] [Plain C I/O] [Type Odds And Ends] [Plain C Strings] [File I/O]
[Functional Average] [Functional Average II] [Functional Average III] [Default Parameters] [Function Overloading] [Reference Parameters] [Constant References] [Namespaces] [Namespaces I] [Using Namespaces]
average4.cpp
#include <iostream>
using namespace std;

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;

        cout << "Enter: ";
        cin >> n1 >> n2 >> n3;

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

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

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

void print_it(int a1, int a2, int a3, double av)
{
        cout << "The average of " << a1 << " " << a2 << " " << a3 
             << " is " << av << endl;
}

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.

This code both C and C++.