函数参数的默认值是“passing_parametr”* 2 [英] Default value of the function parameter is "passing_parametr"*2
问题描述
我写了以下内容:
#include <stdio.h>
int foo(int x, int y=2*x)
{
return y;
}
int main()
{
printf("%d\n",foo(5));
}
但我有编译时错误局部变量'x'可能不会出现在这个上下文中
但我预计它会正常,因为3.3.4 / 1:
But I've compile-time error error: local variable ‘x’ may not appear in this context
But I'm expected that it will be OK, because 3.3.4/1:
在函数声明中或在函数定义(8.4)的
声明符之外的任何函数声明符中,参数名(如果
提供)
In a function declaration, or in any function declarator except the declarator of a function definition (8.4),names of parameters (if supplied) have function prototype scope, which terminates at the end of the nearest enclosing function declarator.
最近的封闭函数声明符的结尾是
。 code>} ,声明点紧接在 int x
之后。那么为什么它不工作?
The end nearest enclosing function declarator is }
, the point of declaration is immediately after int x
. So why it doesn't work?
推荐答案
这不是因为范围。 8.3.6 / 7
说
局部变量不得用于默认参数。
Local variables shall not be used in a default argument.
和 8.3.6 / 9
:
每次调用函数时都会计算默认参数。函数
参数的求值顺序是未指定的。 因此,函数的参数不应在默认参数
中使用,即使它们未被求值。在默认参数之前声明的函数的参数在范围
中,可以隐藏命名空间和类成员名称。
Default arguments are evaluated each time the function is called. The order of evaluation of function arguments is unspecified. Consequently, parameters of a function shall not be used in a default argument, even if they are not evaluated. Parameters of a function declared before a default argument are in scope and can hide namespace and class member names.
禁止此操作是有意义的,因为函数参数的求值顺序未指定。如果 2 * x
将在的参数之前计算,
? y
x
It makes sense to prohibit this, since the order of evaluation of function arguments is unspecified. What would the value of y
be if 2*x
would be evaluated before the argument of x
?
这篇关于函数参数的默认值是“passing_parametr”* 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!