Can an unnamed parameter of function have a default value?

三世轮回 提交于 2019-12-05 18:16:17

问题


Is the following code legal in C++?

void f(void* = 0)
{}

int main()
{
    f();
}

Which page of the C++ standard states that this usage is legal?


回答1:


Yes, it's legal.

There is no standard wording to allow this combination of features specifically; there simply isn't any to disallow it, either.

Default argument syntax applies to function parameters in a parameter-declaration:

[C++11: 8.3.6/1]: If an initializer-clause is specified in a parameter-declaration this initializer-clause is used as a default argument. Default arguments will be used in calls where trailing arguments are missing.

...and function parameters in a parameter-declaration may be unnamed:

[C++11: 8.3.5/11]: [..] An identifier can optionally be provided as a parameter name. [..]

There is even an example of this usage under 8.3.6/4 (though examples are not normative text, so this cannot be used to prove anything concretely).




回答2:


Yes, it's perfectly legal. An obvious example is found in N3485 8.3.6 Default Arguments/4:

[Example: the declaration

void point(int = 3, int = 4);  

declares a function that can be called with zero, one, or two arguments of type int.




回答3:


Yes, it is legal.
The syntax productions given for function parameters in clause 8.3.5/1 allow a parameter declaration without an identifier, but with an assignment expression (as initialiser).




回答4:


Not only is it legal, it could actually be quite useful depending on your coding style.

Default parameters are only meaningful in a function declaration.

Named parameters are only meaningful in a function definition.

f.h:

void f(void*=nullptr);

f.cc

void f(void* x)
{
...
}


来源:https://stackoverflow.com/questions/14675908/can-an-unnamed-parameter-of-function-have-a-default-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!