Put name of parameters in C function prototypes?

eversor picture eversor · Nov 17, 2011 · Viewed 11.5k times · Source

When declaring functions in C, you should set a prototype in which you do not need to write the name of parameters. Just with its type is enough.

     void foo(int, char);

My question is, is it a good practice to also include names of parameters?

Answer

Kerrek SB picture Kerrek SB · Nov 17, 2011

Yes, it's considered good practice to name the arguments even in the prototypes.

You will usually have all your prototypes in the header file, and the header may be the only thing your users ever get to inspect. So having meaningful argument names is the first level of documentation for your API.

Likewise, comments about the what the functions do (not how they're implemented, of course) should go in the header, together with their prototypes.

A well-written header file may be the most important part of your library!


As a curious aside, constness of arguments is an implementation detail. So if you don't mutate an argument variable in your implementation, only put the const in the implementation:

/* Header file */

/* Computes a thingamajig with given base
 * in the given number of steps.
 * Returns half the thingamajig, or -1 on error.
 */
int super_compute(int base, int steps); 

/* implementation file */

#include "theheader.h"

int super_compute(const int base, int steps)
{
  int b = 2 * base;
  while (--steps) { b /= 8; } /* no need for a local variable :-) */
  return -1;
}