Member-only story
C++ — Function default argument value depending on argument name in C++
'y' was not declared in this scope —
function is accepted in Clang, but rejected in GCC
If one defines a new variable in C++, then the name of the variable can be used in the initialization expression, for example:
int x = sizeof(x);
And what about default value of a function argument? Is it allowed there to reference the argument by its name? For example:
void f(int y = sizeof(y)) {}
This function is accepted in Clang, but rejected in GCC with the error:
'y' was not declared in this scope
Which compiler is right here?
Answer
According to the C++17 standard (11.3.6 Default arguments)
9 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. Parameters of a function declared before a default argument are in scope and can hide namespace and class member name
It provides the following example:
int h(int a, int b = sizeof(a)); // OK, unevaluated operand
So, this function declaration
void f(int y = sizeof(y)) {}