I want a function argument to take the value of an other argument as a default value.
My question is: Why am i not allowed to do that ?
void foo(int a, int b = a)
{
}
and is there an other way to do it than that ?
void foo(int a)
{
foo(a,a);
}
void foo(int a, int b)
{
}
- Why am i not allowed to do that ?
Because the evaluation order of function arguments is unspecified, it's not guaranteed that b
will be initialized with the value passed in as the argument of a
.
From $8.3.6/9 Default arguments [dcl.fct.default]:
A default argument is evaluated each time the function is called with no argument for the corresponding parameter. A parameter shall not appear as a potentially-evaluated expression in a default argument.
[ Example:int a; int f(int a, int b = a); // error: parameter a // used as default argument
and
- and is there an other way to do it than that ?
Using function overloading would be simple and fine.