Function Prototypes

In standard C you can declare a function before you define it. The declaration describes the function's name, its return value, and the number and types of its parameters. This feature, called a “function prototype,” allows the compiler to compare the function calls to the prototype and to enforce type checking.

C does not require a prototype for each function. If you omit it, at worst you get a warning. C++, on the other hand, requires every function to have a prototype.

The next example uses a function named display to print “Hello, world.”

// A program without function prototypes

// Note: This will not compile.

#include <iostream.h>

void main()

{

display( "Hello, world" );

}

void display( char *s )

{

cout << s;

}

Because the display function has no prototype, this program does not survive the syntax-checking phase of the C++ compiler.

The next example adds a function prototype to the previous program. Now the program compiles without errors.

A program with a function prototype

#include <iostream.h>

void display( char *s );

void main()

{

display( "Hello, world" );

}

void display( char *s )

{

cout << s;

}

In some C programs, the function definitions declare the types of the parameters between the parameter list and the function body. C++ requires that function definitions declare the types of all parameters within the parameter list. For example:

void display( char *s ) // New style required in C++

{

cout << s;

}

void display( s ) // Error: old style doesn't work

char *s

{

cout << s;

}

If you define a function before you call it, you don't need a separate prototype; the function definition acts as the prototype. However, if you don't define the function until after you call it, or if the function is defined in another file, you must provide a prototype.

Keep in mind that the prototype requirement is an exception to the general rule that a C++ compiler can handle a C program. If your C programs do not have function prototypes and new-style function-declaration blocks, then you must add them before compiling the programs in C++.

Note:

If you need to generate new-style function prototypes for existing C programs, use the CL.EXE program with the /Zg option. See Chapter 13, “CL Command Reference,” in Environment and Tools for more details.