Why do function prototypes include parameter names when they're not required?

Lockhead picture Lockhead · Mar 8, 2011 · Viewed 10.3k times · Source

I always thought that a function prototype must contain the parameters of the function and their names. However, I just tried this out:

int add(int,int);

int main()
{
    std::cout << add(3,1) << std::endl;
}

int add(int x, int y)
{
    return x + y;
}

And it worked! I even tried compiling with extreme over-caution:

g++ -W -Wall -Werror -pedantic test.cpp

And it still worked. So my question is, if you don't need parameter names in function prototypes, why is it so common to do so? Is there any purpose to this? Does it have something to do with the signature of the function?

Answer

Thomas picture Thomas · Mar 8, 2011

No, these are not necessary, and are mostly ignored by the compiler. You can even give them different names in different declarations; the following is entirely legal:

int foo(int bar);
int foo(int biz);
int foo(int qux) {
    ...
}

(The compiler does check that each name is used only once in the same argument list: int foo(int bar, int bar); is rejected.)

The reason to put them in is documentation:

  • If someone reads your header file, they can tell at a glance what each parameter is used for.
  • If you use a fancy IDE, it can show you the parameter names when you begin typing the function call.
  • Documentation tools like Doxygen can parse the parameter names and show them in the documentation.