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?
In a prototype, parameter names are optional (and in C/C++ have function prototype scope, meaning their scope ends at the end of the prototype), however, the type is necessary along with all modifiers (e.g. if it is a pointer or a reference to const parameter) except const alone.
The function name must match exactly the name of the function in the function prototype. The args are a list of values (or variables containing values) that are "passed" into the function. The number of args "passed" into a function must exactly match the number of parameters required for the function.
Of course, the variable names in the definition will be used. Parameters must have names in the definition, but the names are optional in prototypes.
A function prototype is simply a declaration of a new function that provides its name, input parameters (in parentheses), and type of return value (or void, if there is none).
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; }
I definitely recommend including the names of the parameters. If you're writing a library, it is certainly useful for those who will use your library to be able to glean what a function does from its prototype in your header files. Consider memcpy
for instance. Without the names of the parameters, you'd be lost to know which is the source and which is the target. Finally, it is easier to include the names than to remove them when you copy your function definition to make it into a prototype. If you keep the names, you only need to add a semicolon at the end.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With