Why can't existing function arguments be used to evaluate other default arguments?

I wrote a function foo() that takes 2 const char* as arguments, pBegin and pEnd . foo() null-terminated string is passed. By default, pEnd points to the \0 (last character) string.

 void foo (const char *pBegin, const char *pEnd = strchr(pBegin, 0)) // <--- Error { ... } 

However, I get an error message in the line above:

 error: local variable 'pBegin' may not appear in this context 

Why does the compiler not allow such an operation? What is the potential problem?

+6
source share
4 answers

The standard not only explicitly prohibits the use of other parameters in the expression of the default argument, but also explains the reason and gives an example:

ISO / IEC 14882: 2003 (E) - 8.3.6 Default Arguments [dcl.fct.default]

9. The default arguments are evaluated each time the function is called. The evaluation order of the function arguments is not specified. Therefore, function parameters should not be used as default arguments, even if they are not evaluated. Parameters A function declared before the default argument expression in a scope and can hide namespace names and class member names. [Example:

  int a; int f(int a, int b = a); // error: parameter a // used as default argument typedef int I; int g(float I, int b = I(2)); // error: parameter I found int h(int a, int b = sizeof(a)); // error, parameter a used // in default argument 

-end example] ...

+9
source

The language still offers a way to do what you want - to use overloaded functions:

 void foo (const char *pBegin, const char *pEnd) { //... } void foo (const char *pBegin) { foo(pBegin, strchr(pBegin, 0)); } 
+6
source

When a function is called, the arguments are evaluated by default, but the order they evaluate is not defined by the C ++ standard. This means that you cannot refer to other parameters in the default argument, because they may not yet have a known value.

+3
source

You cannot use a local variable in the default argument value.

Quote from here:

The standard tells us that the default argument is just an expression. There are some things that are not allowed (using local variables, using the 'this' keyword), but pretty much anything else can serve as a default argument.

+1
source

Source: https://habr.com/ru/post/907678/


All Articles