Lockhead Lockhead - 1 year ago 74
C++ Question

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

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 Source

No, these are not necessary, and are in fact 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 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.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download