2
#include <iostream>
void fun(int a = sizeof(a)){
    std::cout<< a<<std::endl;
}
int main(){
   fun();
}

Consider this case. Clang accepts it while GCC rejects it. According to [dcl.fct.default] p9

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.

[basic.def.odr] p2

An expression or conversion is potentially evaluated unless it is an unevaluated operand

sizeof is not a potentially-evaluated expression and a can be found at this point. I wonder which one is correct for this case?

xmh0511
  • 7,010
  • 1
  • 9
  • 36
  • 1
    Dup of [Using a parameter's name inside its own default value - is it legal?](https://stackoverflow.com/questions/40513156/using-a-parameters-name-inside-its-own-default-value-is-it-legal) and [Function default argument value depending on argument name in C++](https://stackoverflow.com/questions/69461415/function-default-argument-value-depending-on-argument-name-in-c) – Language Lawyer Feb 10 '22 at 09:56

1 Answers1

1

GCC is wrong. It assumes that a is not yet in scope in the default argument, although generally the point of declaration is immediately after the declarator before the initializer and none of the exceptions apply here. [basic.scope.pdecl]/1

An older bug report for this is here.

Note however, that the bug report has equivalent code to yours, but claims it should be ill-formed. That is because it was written before CWG 2082 which allowed the use of a parameter in an unevaluated context in the default argument.

Related question regarding this GCC bug here.

user17732522
  • 53,019
  • 2
  • 56
  • 105