gpt4 book ai didi

c++ - 函数参数默认值为 "passing_parametr"*2

转载 作者:太空狗 更新时间:2023-10-29 20:25:30 26 4
gpt4 key购买 nike

我写了以下内容:

#include <stdio.h>

int foo(int x, int y=2*x)
{
return y;
}

int main()
{
printf("%d\n",foo(5));
}

但是我有编译时错误error: local variable ‘x’ may not appear in this context但我希望它会好起来,因为 3.3.4/1:

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.

结束最近的封闭函数声明符是,声明点紧跟在int x之后。那么为什么它不起作用?

最佳答案

这不是因为范围。 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*xx 的参数之前计算,y 的值是多少?

关于c++ - 函数参数默认值为 "passing_parametr"*2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23725995/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com