C prototype functions

Function calls in C don’t require a prototype to be visible but it is highly recommended that a correct prototype is in scope.

The reason for this is that if the function definition doesn’t match the types of the function arguments after the default function argument promotions are performed you are highly likely to get undefined behavior.

Having the correct prototype visible means that the compiler can check the arguments of a function call and warn the programmer if there is a mismatch.

C doesn’t allow functions to be overloaded so you can only have a single prototype for any function name.

Default argument promotions can cause unexpected mismatches.

E.g.

int main(int argc, char **argv)
{
    short s = 5;
    float f = 2.3f;
    x(s, f);     // x implicitly declared; default argument promotions performed
    return 0;
}

int x(short t, float g)  // Error: called with an int and a double
{
    return (int)(t + g);
}

In the function call, because x has no visible prototype (yet), s will be promoted to int and f will be promoted to double. These are default argument promotions. This then causes a mismatch when the function is defined with a prototype that takes a short and a float even though these are the original types of the arguments that were passed in.

Functions that take a variable number of arguments (i.e. use , ... syntax) must always have a visible prototype at the point at which they are called.

Leave a Comment