Func Protos with K&R Func Defs

Jonathan I. Kamens jik at athena.mit.edu
Thu Feb 28 13:17:15 AEST 1991


  That may be the easiest way to do things, but it's not legal ANSI C.

  In ANSI C, a function declaration must match its definition.  That means
that if the declaration is prototyped, then the definition must also be
prototyped, with the same types; if the declaration is not prototyped, then
the definition cannot be prototyped either.

  This isn't just a matter of being picky, either; the differences between how
prototyped and unprototyped functions are compiled will cause your programs to
break if your declarations don't match your definitions.  That's why the file
that defines functions should always include the header file that declares
them, so you'll get errors if the declaration and the definition don't match.

  An example of where this might fail.  Suppose that I have this function
definition:

	random(a, b, c, d, e)
	char a, b, c, d, e;
	{
	     printf("%c %c %c %c %c\n", a, b, c, d, e);
	}

Since this is an old-style definition, the compiler will assume when compiling
it that all arguments to the function have been promoted to ints, and will
therefore reference the arguments on the stack accordingly.  Now supposed I
have this file that uses the function defined in the file above:

	extern random(char a, char b, char c, char d, char e);
	
	main()
	{
	     random('a', 'b', 'c', 'd', 'e');
	}

When compiling this file, the compiler may, if it so chooses, only leave one
byte on the stack for each argument.  Since there is a prototype which
declares the arguments as chars, the compiler does not have to promote them or
leave extra space on the stack for them.

  Now, you may get lucky for a while any only run into compilers that leave
tehe same amount of space on the stack for chars and ints.  But eventually
you're going to run into a compiler that doesn't.  And you're going to lose.

  Summary: Function declarations and definitions must match.  If you have
#ifdef's in hour headers to decide whether or not to use prototypes, then you
must #ifdef your definitions similarly.

-- 
Jonathan Kamens			              USnail:
MIT Project Athena				11 Ashford Terrace
jik at Athena.MIT.EDU				Allston, MA  02134
Office: 617-253-8085			      Home: 617-782-0710



More information about the Comp.lang.c mailing list