Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If a lambda is declared inside a default argument, is it different for each call site?

#include <iostream>

int foo(int x = [](){ static int x = 0; return ++x; }()) {
    return x;
};

int main() {
    std::cout << foo() << foo(); // prints "12", not "11"
}

I know that default arguments are evaluated each time a function is called. Does that mean that the lambda type is different on each call? Please point to the standard quotes explaining the behaviour here.

like image 666
cppbest Avatar asked Aug 31 '25 03:08

cppbest


1 Answers

This example from dcl.fct.default makes pretty clear that the intent is that the point where the default argument is defined also defines the semantics:

int a = 1;
int f(int);
int g(int x = f(a));            // default argument: f(​::​a)

void h() {
  a = 2;
  {
    int a = 3;
    g();                        // g(f(​::​a))
  }
}

In particular, the default argument is not just a token sequence that is inserted at the point of the function call and then analysed.

Following this intent, the lambda expression is analysed at the point of definition of the default argument, not at the point of function call. Therefore, there is only one lambda type, not many, and the correct result is 12.

The Standard doesn't express this clearly enough with regards to lambda expressions being used as default arguments, though.

like image 143
j6t Avatar answered Sep 02 '25 17:09

j6t