I have learnt that function parameters can have default arguments. So I wrote up the below shown program that compiles with some compilers but not with other. I want to know why is this so. That is, what is the right compiler.
void f(int i, int j = decltype(i){})
{
}
int main()
{
f(1);
}
I expected all compilers to agree.
example.cpp
<source>(1): error C2587: 'i': illegal use of local variable as default parameter
<source>(1): note: see declaration of 'i'
<source>(4): error C2660: 'f': function does not take 1 arguments
<source>(1): note: see declaration of 'f'
<source>(4): note: while trying to match the argument list '(int)'
Compiler returned: 2
This is CWG2082 and the program is well-formed. We have from Default arguments documentation:
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 names.
int h(int a, int b = sizeof(a));
(emphasis mine)
This means that the given program is well-formed since i
in decltype(i)
is unevaluated. So gcc and clang are correct in accepting the program.
Here is the msvc bug: