What happens when a function prototype is missing?
Here's a program that is missing a function prototypes. It
does compile, however, in some C compilers. The compiled program
produces strange output, though.
Many C compilers make assumptions about functions that are
called before they are defined or declared via a function prototype
(e.g., that they always return an int ).
The modified program works correctly when the function
prototype for Add3 is added.
The Buggy Program
/* File: proto.c
Demonstrate the need for prototypes
This is the buggy version.
*/
#include
/* No prototypes in this version */
main()
{
double x;
int n, m;
x = Add3 (5.0);
printf("x = %f\n", x);
n = Add3 (10.0);
printf("n = %d\n", n);
m = (int) Add3 (17.0);
printf("m = %d\n", m);
}
/* The function Add3 adds 3.0 to the
value passed into y and returns that
sum back to the calling function. */
double Add3 (double y)
{
double z;
z = y + 3.0;
return (z);
}
The Sample Run
x = 0.000000
n = 13
m = 7
The Fixed Program
/* File: proto2.c
Demonstrate the need for prototypes
This is the corrected version.
*/
#include
/* Include the prototype in this version */
double Add3(double);
main ()
{
double x;
int n, m;
x = Add3 (5.0);
printf ("x = %f\n", x);
n = Add3 (10.0);
printf ("n = %d\n", n);
m = (int) Add3 (17.0);
printf ("m = %d\n", m);
}
/* The function Add3 adds 3.0 to the
value passed into y and returns that
sum back to the calling function. */
double Add3 (double y)
{
double z;
z = y + 3.0;
return (z);
}
The Sample Run
x = 8.000000
n = 13
m = 20
The Lesson
Function prototypes are essential in C.
The C compiler only makes one pass over the source code,
generating object code as it goes. So, it really needs to know the
type a function returns and the types of its arguments before it hits the first call to the function.