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

2023-10-17C/C++开发问题
1

本文介绍了省略参数名称,C++ vs C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

在 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6