C Programming

FUNCTION PROTOTYPES
These have been introduced into the C language as a means of provided type checking and parameter checking for function calls. Because C programs are generally split up over a number of different source files which are independently compiled, then linked together to generate a run-time program, it is possible for errors to occur.

Consider the following example.


	/* source file add.c */
	void add_up( int numbers[20] )
	{
		....
	}

	/* source file mainline.c */
	static float values[] = { 10.2, 32.1, 0.006, 31.08 };

	main()
	{
		float result;
		...
		result = add_up( values );
	}

As the two source files are compiled separately, the compiler generates correct code based upon what the programmer has written. When compiling mainline.c, the compiler assumes that the function add_up accepts an array of float variables and returns a float. When the two portions are combined and ran as a unit, the program will definitely not work as intended.

To provide a means of combating these conflicts, ANSI C has function prototyping. Just as data types need to be declared, functions are declared also. The function prototype for the above is,


	/* source file mainline.c */
	void add_up( int numbers[20] );

NOTE that the function prototype ends with a semi-colon; in this way we can tell its a declaration of a function type, not the function code. If mainline.c was re-compiled, errors would be generated by the call in the main section which references add_up().

Generally, when developing a large program, a separate file would be used to contain all the function prototypes. This file can then be included by the compiler to enforce type and parameter checking.


©Copyright B Brown. 1984-1999. All rights reserved.