### Require Function Prototypes

(ISO C, §6.7.5.3, §6.9.1) The C compiler lets you choose how to enforce function prototypes. The Require Function Prototypes setting controls this behavior.

If you enable the Require Function Prototypes setting, the compiler generates an error if you define a previously referenced function that does not have a prototype. If you define the function before it is referenced but do not give it a prototype, then enabling the Require Function Prototypes setting causes the compiler to issue a warning.

This setting helps you prevent errors that happen when you call a function before you declare or define it. For example, without a function prototype, you might pass data of the wrong type. As a result, your code might not work as you expect even though it compiles without error.

In Listing 1, PrintNum() is called with an integer argument but later defined to take a floating-point argument.

##### Listing 1. Unnoticed Type-mismatch

#include <stdio.h>
void main(void)
{
PrintNum(1); // PrintNum() tries to interpret the
integer as a float. Prints 0.000000.
}

void PrintNum(float x)
{
printf("%f\n", x);
}

When you run this program, you could get this result:

0.000000

Although the compiler does not complain about the type mismatch, the function does not work as you want. Since PrintNum() does not have a prototype, the compiler does not know to convert the integer to a floating-point number before calling the function. Instead, the function interprets the bits it received as a floating-point number and prints nonsense.

If you prototype PrintNum() first, as in Listing 2, the compiler converts its argument to a floating-point number, and the function prints what you wanted.

##### Listing 2. Using a Prototype to Avoid Type-mismatch

#include <stdio.h>
void PrintNum(float x); // Function prototype.

void main(void)
{
PrintNum(1); // Compiler converts int to float.
} // Prints 1.000000.

void PrintNum(float x)
{
printf("%f\n", x);
}

In the above example, the compiler automatically typecasts the passed value. In other situations where automatic typecasting is not available, the compiler generates an error if an argument does not match the data type required by a function prototype. Such a mismatched data type error is easy to locate at compile time. If you do not use prototypes, you do not get a compiler error.

However, at runtime the code might produce an unexpected result whose cause can be extremely difficult to find.

The Require Function Prototypes setting corresponds to the pragma require_prototypes. To check this setting, use __option (require_prototypes). By default, this setting is enabled.

See also “require_prototypes”, and Checking Settings.