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

不想你离开。 提交于 2019-11-27 20:50:13

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.

Parameter names are completely optional, and have no effect on compilation. They may be placed there for better readability of code.

You don't need parameter names in declarations. They are purely documentation.

You don't even need names in definitions:

int f(int)
{
    return 0;
}

compiles just fine in C++ (though not in C). This is sometimes useful for e.g. inheritance, overloading, function pointers.

You do not need to include parameter names in function prototypes. You only need the complete signature, which includes the types of parameters and (in the case of function template specializations) return values.

However, it is still common to include parameter names in order to write self-documenting code. That is, a function with this declaration:

void foo(int number_of_foos_desired, string foo_replacement);

is easier to understand by looking only at the prototype, perhaps, than this one:

void foo(int, string);

Many modern IDEs will also pop up the parameter names as you type when you write code that calls this function. They may not be able to pop up this information if you dont include the parameter names in the prototype.

It has alot to do with the signature of the function.

One of the benefits of using .h files is that when someone comes along and wants to get a sense of what your program/api does, they can look at your header file and get a sense of what operations are being carried out, their inputs and outputs, how everything is going together, etc.

If you were to come across a method like

int doStuff(int,int)

this would be alot less telling than a method with a signature of say:

int doStuff(int firstNumberToAdd, int secondNumberToAdd);

with the second, you at least get some idea of the operations that are being carried out, and what is happening. This is the idea behind writing self documenting code.

If your interested, you may check out Code Complete by Steve McConnell.

There are different scenarios to it. I found it very helpful in dealing with inheritance and virtual functions. If you're using a virtual function that generates unused warning in sub class, you can omit the variable names.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!