在 C++ 中,在某些情况下,我倾向于省略参数的名称。但是在 C 语言中,当我省略参数的名称时出现错误。
代码如下:
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;
}
这是为什么呢? C函数定义中不能省略参数名吗?
最佳答案
不,在 C 中,您不能在函数定义中省略参数标识符。
C99 标准说:
[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.
C++14 标准说:
[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.]
关于c++ - 省略参数名称,C++ vs C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8776810/