Thursday, July 28, 2022

[SOLVED] Is GCC or Clang correct about the name of a function parameter being in scope in its own default argument?

Issue

I have a little toy program:

static int value = 0;

int function(int &value=value) {
    return value;
}

int main() {
    function();
}

Compiling with g++ 7.2:

g++ -std=c++11 -Wall -Wextra test.cc -o test

No problem.

Compiling with clang++-3.9:

clang++-3.9 -std=c++11 -Wall -Wextra test.cc -o test

test.cc:3:25: error: default argument references parameter 'value'
int function(int &value=value) {
                        ^~~~~
test.cc:8:5: error: no matching function for call to 'function'
    function();
    ^~~~~~~~
test.cc:3:5: note: candidate function not viable: requires single argument 'value', but no arguments were provided
int function(int &value=value) {
    ^
2 errors generated.

Kaboom. Who's right?


Solution

I think clang is correct. From basic.scope.pdecl:

The point of declaration for a name is immediately after its complete declarator (Clause [dcl.decl]) and before its initializer (if any), except as noted below. [ Example:

int x = 12;{ int x = x; }

Here the second x is initialized with its own (indeterminate) value. — end example ]

Also, from dcl.fct.default:

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



Answered By - R Sahu
Answer Checked By - Clifford M. (WPSolving Volunteer)