Default value of the function parameter is “passin

2019-05-15 00:05发布

I wrote the following:

#include <stdio.h>

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

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

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:

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.

The end nearest enclosing function declarator is }, the point of declaration is immediately after int x. So why it doesn't work?

3条回答
对你真心纯属浪费
2楼-- · 2019-05-15 00:45

This is not because of scope. 8.3.6/7 says that

Local variables shall not be used in a default argument.

and 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.

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?

查看更多
爷、活的狠高调
3楼-- · 2019-05-15 00:54

Does this snippet work for you?

#include <stdio.h>

int foo(int x, int y)
{
    return y;
}

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

int main()
{
    printf("%d\n",foo(5));
}
查看更多
祖国的老花朵
4楼-- · 2019-05-15 00:55

you are sending one arg to foo function when you have written it taking 2 param this way it should work :

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

int main()
{
    printf("%d\n",foo(5));
}
查看更多
登录 后发表回答