I was writing a function foo()
which takes 2 const char*
s as arguments, pBegin
and pEnd
. foo()
is passed a null terminated string. By default pEnd
points to \0
(last character) of the string.
void foo (const char *pBegin,
const char *pEnd = strchr(pBegin, 0)) // <--- Error
{
...
}
However, I get an error at above line as:
error: local variable ‘pBegin’ may not appear in this context
Why compiler doesn't allow such operation ? What's the potential problem ?
Default arguments are only allowed in the parameter lists of function declarations and lambda-expressions, (since C++11) and are not allowed in the declarations of pointers to functions, references to functions, or in typedef declarations.
Only the argument at the end of the argument list can have default arguments. Because if you insert the default arguments at the middle of the argument list, the compiler would lose track of what arguments went where. void badfunc(int, int=2,int) // Wrong way... void okfunc(int, int=2, int=5); // Correct.
Default arguments are useful when we want to increase the capabilities of an existing function as we can do it just by adding another default argument to the function. It helps in reducing the size of a program. It provides a simple and effective programming approach.
A default argument is a value in the function declaration automatically assigned by the compiler if the calling function does not pass any value to that argument. The values passed in the default arguments are not constant. These values can be overwritten if the value is passed to the function.
The standard not only explicitly disallows the use of other parameters in a default argument expression, but also explains why and gives an example:
ISO/IEC 14882:2003(E) - 8.3.6 Default arguments [dcl.fct.default]
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 default argument expressions, even if they are not evaluated. Parameters of a function declared before a default argument expression 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 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] ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With