title: Lambda returning itself: is this legal?
body: <p>Consider this fairly useless program:</p>
  
  <pre><code>#include &lt;iostream&gt;
  int main(int argc, char* argv[]) {
  
    int a = 5;
  
    auto it = [&amp;](auto self) {
        return [&amp;](auto b) {
          std::cout &lt;&lt; (a + b) &lt;&lt; std::endl;
          return self(self);
        };
    };
    it(it)(4)(6)(42)(77)(999);
  }
  </code></pre>
  
  <p>Basically we are trying to make a lambda that returns itself. </p>
  
  <ul>
  <li>MSVC compiles the program, and it runs</li>
  <li>gcc compiles the program, and it segfaults</li>
  <li>clang rejects the program with a message:
  
  <blockquote>
    <p><code>error: function 'operator()&lt;(lambda at lam.cpp:6:13)&gt;' with deduced return type cannot be used before it is defined</code></p>
  </blockquote></li>
  </ul>
  
  <p>Which compiler is right? Is there a static constraint violation, UB, or neither?</p>
  
  <p><strong>Update</strong> this slight modification is accepted by clang:</p>
  
  <pre><code>  auto it = [&amp;](auto&amp; self, auto b) {
            std::cout &lt;&lt; (a + b) &lt;&lt; std::endl;
            return [&amp;](auto p) { return self(self,p); };
    };
    it(it,4)(6)(42)(77)(999);
  </code></pre>
  
  <p><strong>Update 2</strong>: I understand how to write a functor that returns itself, or how to use the Y combinator, to achieve this. This is more a language-lawyer question.</p>
  
  <p><strong>Update 3</strong>: the question is <em>not</em> whether it is legal for a lambda to return itself in general, but about the legality of this specific way of doing this. </p>
  
  <p>Related question: <a href="https://stackoverflow.com/questions/52173762/c-lambda-returning-itself">C++ lambda returning itself</a>.</p>