Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parameter name omitted, C++ vs C

Tags:

c++

c

compilation

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?

like image 624
Alcott Avatar asked Jan 08 '12 10:01

Alcott


2 Answers

No, in C you cannot omit identifiers for parameters in function definitions.

The C99 standard says:

[6.9.1.5] If the declarator includes a parameter type list, the declaration of each parameter shall include an identifier, except for the special case of a parameter list consisting of a single parameter of type void, in which case there shall not be an identifier. No declaration list shall follow.

The C++14 standard says:

[8.3.5.11] An identifier can optionally be provided as a parameter name; if present in a function definition , it names a parameter (sometimes called “formal argument”). [Note: In particular, parameter names are also optional in function definitions and names used for a parameter in different declarations and the definition of a function need not be the same.]

like image 139
adl Avatar answered Sep 18 '22 02:09

adl


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.)

UPDATE: It's likely that the next edition of the C standard will allow parameter names to be omitted.

like image 22
Keith Thompson Avatar answered Sep 21 '22 02:09

Keith Thompson