Hacker News new | ask | show | jobs
by sltkr 63 days ago
C++ lambdas are just structs that overload operator(); once you realize that they become a lot less mysterious. But it's a great example of how this tool is useful to learn about those things (of course you could also read the C++ standard but who has time for that?)

Here's an example: https://cppinsights.io/s/f04b6896

(That also shows how C++'s range-based for-loops work, which is similarly some syntactic suger for a fairly mundane for-loop, but details are interesting: unlike a typical for-loop, the loop variable is declared inside the loop body.)

2 comments

I said shows a lambda _capture_. This involves the compiler automatically determining which variables cross the scope boundary, and injecting code for each one.
I'm curious to understand which part you think is particularly interesting. The compiler clearly knows which variables are declared in what scope, so what's mysterious about figuring out which values need to be captured?
> That also shows how C++'s range-based for-loops work, which is similarly some syntactic suger for a fairly mundane for-loop, but details are interesting: unlike a typical for-loop, the loop variable is declared inside the loop body

That’s not true in C++, is it? There, this does not compile

  for(int i = 0; i < 3; ++i)
  {}
  i = i + 1;
(https://cppinsights.io/s/26405687: error: use of undeclared identifier 'i')

https://en.cppreference.com/cpp/language/for:

“A for statement equivalent to:

  {
    init-statement
    while ( condition )
    {
      statement
      expression ;
    }
  }
Except that […]”

and

“While in C names declared in the scope of init-statement and condition can be shadowed in the scope of statement, it is forbidden in C++:

  for (int i = 0;;)
  {
    long i = 1;   // valid C, invalid C++
    // ...
  }
“