In C++, I tend to omit the parameter's name under some circumstances. But in C, I got an error when I omitted the parameter's name.
Here is the code:
void foo(int); //forward-decl, it's OK to omit the parameter's name, in both C++ and C
int main()
{
foo(0);
return 0;
}
void foo(int) //definition in C, it cannot compile with gcc
{
printf("in foo\n");
}
void foo(int) //definition in C++, it can compile with g++
{
cout << "in foo" << endl;
}
Why is that? Can't I omit the parameter's name in C function definition?
The reason is that that's what the respective language standards say, but there is a rationale for the difference.
If you don't provide a name for a parameter, then the function cannot refer to that parameter.
In C, if a function ignores one of its parameters, it usually makes sense just to remove it from the declaration and the definition, and not pass it in any calls. An exception might be a callback function, where a collection of functions all have to be of the same type but not all of them necessarily use their parameters. But that's not a very common scenario.
In C++, if the function is derived from a function defined in some parent class, it has to have the same signature as the parent, even if the child function has no use for one of the parameter values.
(Note that this is not related to default parameters; if a parameter in C++ has a default value, the caller doesn't have to pass it explicitly, but the function definition still has to provide a name if it's going to refer to it.)
On a purely practical level, I have deal with this daily. The best solution to date is to use the pre-processor. My common header file contains:
An example of the use of UNUSED is:
Sometimes you actually need to refer to the parameter, for example in an assert() or debug statement. You can do so via:
Also, the following are useful:
Examples:
and:
You can omit the parameter name in the function prototype, but you must declare it in the function implementation. For example, this compiles and runs just fine under GCC 4.6.1
Outputs:
In foo with value 10 and 15!
As to why (other than because the standards say so): C++ allows you to call a function without using all of the arguments, while C doesn't. If you don't supply all the arguments to a function in C, then the compiler will throw
error: too few arguments to function 'foo'
No, in C you cannot omit identifiers for parameters in function definitions.
The C99 standard says:
The C++14 standard says: