1

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)
{

}
tchekof
  • 13
  • 2

2 Answers2

1

Using

void foo(int a, int b = a) { ... }

is an error as per the standard.

From the C++11 Standard:

8.3.6 Default arguments

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. [ Example:

int a;
int f(int a, int b = a); // error: parameter a
                         // used as default argument

...

— end example ]

R Sahu
  • 204,454
  • 14
  • 159
  • 270
0
  1. 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

  1. and is there an other way to do it than that ?

Using function overloading would be simple and fine.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405