This book explains how to declare and define functions under the ANSI standard for C, which is now the norm. The original C language used slightly different rules for function declarations and definitions. QuickC can compile these “old-style” programs, but the ANSI standard recommends you use the full function prototypes we just described.
Still, you may encounter old-style function declarations and definitions in many existing C programs. So, you should be familiar with the style.
We'll use the VOLUME.C program from Chapter 1, “Anatomy of a C Program,” to demonstrate the old style. First, here's the ANSI-style program presented in Chapter 1:
/* VOLUME.C: Calculate sphere's volume. */
#include <stdio.h>
#define PI 3.14
float sphere( int rad );
main()
{
float volume;
int radius = 3;
volume = sphere( radius );
printf( "Volume: %f\n", volume );
}
float sphere( int rad )
{
float result;
result = rad * rad * rad;
result = 4 * PI * result;
result = result / 3;
return result;
}
The same program written in the old style would look something like this:
/* OLDSTYLE.C: Old-style function. */
#include <stdio.h>
#define PI 3.14
float sphere();
main()
{
float volume;
int radius = 3;
volume = sphere( radius );
printf( "Volume: %f\n", volume );
}
float sphere( rad )
int rad;
{
float result;
result = rad * rad * rad;
result = 4 * PI * result;
result = result / 3;
return result;
}
You'll notice two distinct differences. First, the old style doesn't allow a para-meter list in the function declaration. In the ANSI version, VOLUME.C, the declaration of the sphere function specifies that the function takes a single int parameter:
float sphere( int rad );
The corresponding declaration in OLDSTYLE.C omits the parameter list:
float sphere();
An old-style function declaration cannot provide any information about the function's parameters.
The other change is in the way the function definition lists parameters. In VOLUME.C, the function header lists the same information as the function prototype, giving the type (int) and name (rad) of the function's parameter:
float sphere( int rad )
{
.
.
.
}
In OLDSTYLE.C, the function header gives the parameter's name ( rad ), but not its type. The parameter's type is declared in a statement directly below the function header (and before the left brace that begins the function body):
float sphere( rad )
int rad;
{
.
.
.
}
The rest of OLDSTYLE.C is identical to VOLUME.C.
Now that you understand the basics of functions, we can turn our attention to the C statements that a function can contain, beginning with flow-control statements, the subject of the next chapter.