Table of Contents
Previous Section Next Section

Prototypes

In C++, all functions must be prototyped. In C, prototypes are technically optional, but strongly recommended. The general form of a prototype is shown here:

ret-type name(parameter list);

In essence, a prototype is simply the return type, name, and parameter list of a function, followed by a semicolon.

The following example shows how the function fn( ) is prototyped:

float fn(float x); // prototype 

  .
  .
  .
// function definition
float fn(float x)
{
  // ...
}

To specify the prototype for a function that takes a variable number of arguments, use three periods at the point at which the variable number of parameters begin. For example, the printf( ) function could be prototyped like this:

int printf(const char *format, ...);

When specifying the prototype to an overloaded function, each version of that function must have its own prototype. When a member function is declared within its class, this constitutes a prototype for the function.

In C, to specify the prototype for a function that has no parameters, use void in its parameter list. For example,

int f(void);

In C++, an empty parameter list in a prototype means that the function has no parameters; the void is optional. Thus, in C++, the preceding prototype can be written like this:

int f();

In C++, you can include void in the parameter list, but doing so is redundant.

Programming Tip 

Two terms are commonly confused in C/C++ programming: declaration and definition. Here is what they mean. A declaration specifies the name and type of an object. A definition allocates storage for it. These definitions apply to functions, too. A function declaration (prototype) specifies the return type, name, and parameters of a function. The function itself (that is, the function with its body) is its definition.

In many cases, a declaration is also a definition. For example, when a non-extern variable is declared, it is also defined. Or, when a function is defined prior to its first use, its definition also serves as its declaration.


Table of Contents
Previous Section Next Section