问题描述
在 C++ 中,我倾向于在某些情况下省略参数的名称.但是在 C 中,当我省略参数名称时出现错误.
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.
代码如下:
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
");
}
void foo(int) //definition in C++, it can compile with g++
{
cout << "in foo" << endl;
}
这是为什么?我不能在 C 函数定义中省略参数名称吗?
Why is that? Can't I omit the parameter's name in C function definition?
推荐答案
不,在 C 中你不能省略函数定义中参数的标识符.
No, in C you cannot omit identifiers for parameters in function definitions.
C99 标准说:
[6.9.1.5] 如果声明符包含参数类型列表,则每个参数的声明应包括一个标识符,除了由单个参数组成的参数列表的特殊情况void 类型,在这种情况下不应有标识符.不申报清单如下.
[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] 可以选择将标识符作为参数提供名称;如果出现在函数定义中,它会命名一个参数(有时称为正式论证").[注:特别是参数名称在函数定义中也是可选的,名称用于不同声明中的参数和函数的定义不必相同.]
[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++ vs C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!