c++ - 省略参数名称,C++ vs C

标签 c++ c compilation

在 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/

相关文章:

c++ - MFC/Sql 相同情况下的不同异常

android - 如何将现有的仅 header 源文件添加到 android studio?

c++ - "Error: incomplete type "unsigned char[] ""在 Solaris 机器上用 SUN C++ 编译时

c - Linux系统如何处理文件中的CRLF?

c++ - 如何编辑 QSqlTableModel 中的特定列

c++ - 使用 boost 实现 C++11 lambda

c++ - 如何在从声明 View 接收到的 QML 对象上设置事件监听器?

c - 哪个函数告诉我内核将本地套接字绑定(bind)到哪个地址?

c - 嵌入式c和8051微 Controller

c++ - 如何导出到我的 mac (C++) 上的 vsproject?