Search code examples
language-agnosticfunction-prototypes

What are prototypes in programming?


This isn't a specific question about a language, but more about programming in general. The question came after I started an argument with a friend about "Function prototypes" which I learnt about recently from my C++ course. I mentioned to him that prototypes are function headers that you have to create at the beginning of your code so the compiler allocates some space at runtime before getting to the actual function. We then started rambling about whether other programming languages (Like java or python) which do not utilize function prototypes -- so far as we're concerned -- actually had a system similar to that of C++, just that they handled it themselves rather than having the user create them.

So we're curious to know, what are function prototypes after all? Are they only accountable on C/C++, or do other programming languages make use of them? And is it something I'd need to develop more on as a future programmer? Thanks for the help!


Solution

  • With respect to C and C++, the word "prototype" refers to a specific declaration syntax.

    In the earliest versions of C, function definitions were written as

    int func( arg1, arg2, arg3 ) // no types in argument list, just identifiers
      int arg1;
      double arg2;
      char *arg3;
    {
      // function body
    }
    

    and declarations were written as

    int func( ); // no argument list
    

    The function argument list only contained identifiers and no type information - that was supplied separately. Function declarations didn't include arguments, just the return type.

    C++ introduced and C later adopted the concept of prototype syntax, where the type information is included in the parameter list in both the definition:

    int func( int arg1, double arg2, char *arg3 )
    {
      // function body
    }
    

    and the declaration

    int func( int, double, char * );
    

    This allowed compilers to check the number and types of arguments in a function call and issue diagnostics if they didn't match, rather than waiting until runtime to find out if there's a problem.

    While the old-style function declaration and definition syntax is still supported, it should not be used for new code development - we're almost to the point where the word "prototype" is kind of redundant, since prototype syntax is the norm rather than the exception.

    Statically-typed languages like Fortran and Pascal and Ada all have separate function declarations, but they don't refer to those declarations as prototypes. And again with C, "prototype" refers to a specific style of function declaration and definition, not just a declaration in and of itself.