by alexey-salmin · 2mo ago · 0 comments
Without all this nested functions are as useful as the "rewritten" examples in the article, one can easily do that by hand without any compiler or language support.
This problem doesn't arise with C++ lambdas because you pass them around as special objects, not as bare function pointers.
For my part, I'll point out that there is one rather important difference between nested functions and C++ lambdas that the author completely ignores, as exhibited by this godbolt example: https://godbolt.org/z/35beWrrTe (note the differences in the generated assembly, especially that which cannot be explained merely by -O0 code generation).
Do you mind elaborating for those of us who aren't familiar with what to expect from the compiler?
BTW: I also very carefully analyzed all the semantic differences, which led me to the conclusion that putting C++ lambda semantics into C would be a bad idea. one can read this here: https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3654.pdf
I also do not understand why you think the generated assembly needs to be identical, or why this is a "rather important difference".
If they don't capture anything, I believe you _can_ pass them as bare function pointers.
This one explains how you can avoid the use of trampolines in GCC 17: https://uecker.codeberg.page/2026-07-14.html
The documentation is here: https://gcc.gnu.org/onlinedocs/gcc/Constructing-Calls.html
There are many language features can be rewritten by hand into other simpler forms, you could rewrite loops into gotos, C++ objects into structures, etc. This does not show that those things are not useful. But the point of the article was not to show why nested functions are useful, for which I would certainly have used more interesting examples.
Also misses that the way C++ lambdas work is that one design requirement was that they should be syntax sugar for the functor[0] pattern from C++98.
[0] - Not to mix with ML functors, rather classes with call operator overloaded.