From Matthew Probert · 1996-04-04 22:25 · #75208 in R25C
THE IMPORTANCE OF PROTOTYPING C PROGRAMS
Matthew Probert
Servile Software
Prototyping a function involves letting the C compiler know in advance
what type of values a function will receive and return. For example,
lets look at strtok(). This has the prototype;
char *strtok(char *s1, const char *s2);
This prototype tells the compiler that strtok() will return a
character pointer, the first received parameter will be a pointer to a
character string, and that string can be changed by strtok(), and the
last parameter will be a pointer to a character string that strtok()
cannot change.
The compiler knows how much space to allocate for the return
parameter, sizeof(char *), but without a prototype for the function
the compiler will assume that the return value of strtok() is an
integer, and will allocate space for a return type of int, that is
sizeof(int). If an integer and a character pointer occupy the same
number of bytes on the host computer no major problems will occur, but
if a character pointer occupies more space than an integer, then the
compiler wont have allocated enough space for the return value and the
return from a call to strtok() will overwrite some other bit of
memory. If, as so often happens the return value is returned via the
stack, the results of confusing the compiler can be disastrous!
Thankfully most C compilers will warn the programmer if a call to a
function has been made without a prototype, so that you can add the
required function prototypes.
Consider the following example that will not compile on most modern C
compilers due to the nasty error in it;
#include <stdio.h>
int FUNCA(int x, int y)
{
return(MULT(x,y));
}
double MULT(double x, double y)
{
return(x * y);
}
main()
{
printf("\n%d",FUNCA(5,5));
}
When the compiler first encounters the function MULT() it is as a call
from within FUNCA(). In the absence of any prototype for MULT() the
compiler assumes that MULT() returns an integer. When the compiler
finds the definition for function MULT() it sees that a return of type
double has been declared. The compiler then reports an error in the
compilation saying something like;
"Type mismatch in redclaration of function 'MULT'"
What the compiler is really trying to say is, prototype your functions
before using them! If this example did compile, and was then run it
probably would crash the computer's stack and cause a system hang.
... [Servile Info Journal]
___ Blue Wave/QWK v2.12
--- WILDMAIL!/WC v4.12
* Origin: Ooh! BBS, London [MULTILINES] 0181-395-3108 (2:254/233.0)