There are two basic ways to implement closures: A custom calling convention: Callers are aware they're calling a closure and so pass the closure context to the callee, perhaps as a hidden argument. Closures are nearly always implemented this way, including in C++. For C, as a lingua franca platforms would need to define this calling convention / ABI so that different implementers could all each others closures just as they can call each others functions. Since this doesn't exist, closures in language implementations using this approach are incompatible with C interop (ex. can't turn a C++ closure into a function pointer). Build a trampoline by allocating a little bit of executable memory, essentially like using a small JIT compiler. Callers do not need to be aware they're calling a closure, and a plain C calling convention is sufficient. GNU C closures are implemented this way, as are CPython's ctypes callbacks. However, frequently allocating executable memory requires significant trade-offs in performance or security. It may not even be possible on some platforms. This is also an implicit allocation — which is not in the spirit of C — and someone has to manage its lifetime. (GNU C manages it by using an automatic allocation.) Unless you're willing to make the trade-offs in the second approach — which is available to you if you use GCC — neither fits C well. Answer from skeeto on reddit.com
🌐
GeeksforGeeks
geeksforgeeks.org › c++ › lambda-expression-in-c
Lambda Expression in C++ - GeeksforGeeks
Lambda expressions in C++ are anonymous, inline functions introduced in C++11 that allow writing small pieces of logic directly at the place of use.
Published   1 month ago
🌐
Microsoft Learn
learn.microsoft.com › en-us › cpp › cpp › lambda-expressions-in-cpp
Lambda expressions in C++ | Microsoft Learn
In C++11 and later, a lambda expression—often called a lambda—is a convenient way of defining an anonymous function object (a closure) right at the location where it's invoked or passed as an argument to a function.
🌐
Reddit
reddit.com › r/c_programming › why does c not have lambdas/anonymous function expressions?
r/C_Programming on Reddit: Why does C not have lambdas/anonymous function expressions?
August 7, 2022 -

It would not seem to hard to implement to allow a programmer to use a construct similar to:

int (*add)(int, int) = (int(int x, int y)){return x+y;};

This would simplify code that requires callback functions such as qsort or bsearch or various UI libraries that use callbacks to define, for example, a buttons behavior when pressed. Is there any specific reason they elected not to support this, and require us to define named static functions instead?

Top answer
1 of 7
6
There are two basic ways to implement closures: A custom calling convention: Callers are aware they're calling a closure and so pass the closure context to the callee, perhaps as a hidden argument. Closures are nearly always implemented this way, including in C++. For C, as a lingua franca platforms would need to define this calling convention / ABI so that different implementers could all each others closures just as they can call each others functions. Since this doesn't exist, closures in language implementations using this approach are incompatible with C interop (ex. can't turn a C++ closure into a function pointer). Build a trampoline by allocating a little bit of executable memory, essentially like using a small JIT compiler. Callers do not need to be aware they're calling a closure, and a plain C calling convention is sufficient. GNU C closures are implemented this way, as are CPython's ctypes callbacks. However, frequently allocating executable memory requires significant trade-offs in performance or security. It may not even be possible on some platforms. This is also an implicit allocation — which is not in the spirit of C — and someone has to manage its lifetime. (GNU C manages it by using an automatic allocation.) Unless you're willing to make the trade-offs in the second approach — which is available to you if you use GCC — neither fits C well.
2 of 7
5
Why are people obsessed with making C like python or whatever language they learned first? It's like asking why my bicycle only has two wheels, when your red wagon has four.
Top answer
1 of 2
10

This behavior seems to be specfic to newer versions of Clang, and is a language extension called "blocks".

The Wikipedia article on C "blocks" also provides information which supports this claim:

Blocks are a non-standard extension added by Apple Inc. to Clang's implementations of the C, C++, and Objective-C programming languages that uses a lambda expression-like syntax to create closures within these languages. Blocks are supported for programs developed for Mac OS X 10.6+ and iOS 4.0+, although third-party runtimes allow use on Mac OS X 10.5 and iOS 2.2+ and non-Apple systems.

Emphasis above is mine. On Clang's language extension page, under the "Block type" section, it gives a brief overview of what the Block type is:

Like function types, the Block type is a pair consisting of a result value type and a list of parameter types very similar to a function type. Blocks are intended to be used much like functions with the key distinction being that in addition to executable code they also contain various variable bindings to automatic (stack) or managed (heap) memory.

GCC also has something similar to blocks called lexically scoped nested functions. However, there are some key differences also note in the Wikipedia articles on C blocks:

Blocks bear a superficial resemblance to GCC's extension of C to support lexically scoped nested functions. However, GCC's nested functions, unlike blocks, must not be called after the containing scope has exited, as that would result in undefined behavior.

GCC-style nested functions also require dynamic creation of executable thunks when taking the address of the nested function. [...].

Emphasis above is mine.

2 of 2
7

the C standard does not define lambdas at all but the implementations can add extensions.

Gcc also added an extension in order for the programming languages that support lambdas with static scope to be able to convert them easily toward C and compile closures directly.

Here is an example of extension of gcc that implements closures.

#include <stdio.h>

int(*mk_counter(int x))(void)
{
    int inside(void) {
        return ++x;
    }
    return inside;
}

int
main() {
    int (*counter)(void)=mk_counter(1);
    int x;
    x=counter();
    x=counter();
    x=counter();
    printf("%d\n", x);
    return 0;
}
🌐
Hackaday
hackaday.com › 2019 › 09 › 11 › lambdas-for-c-sort-of
Lambdas For C — Sort Of | Hackaday
November 2, 2023 - Modern C++ has lambda expressions. However, in C you have to define a function by name and pass a pointer — not a huge problem, but it can get messy if you have a lot of callback functions that you use only one time. It’s just hard to think up that many disposable function names.
🌐
Cppreference
en.cppreference.com › w › cpp › language › lambda.html
Lambda expressions (since C++11) - cppreference.com
The lambda expression is a prvalue expression of unique unnamed non-union non-aggregate class type, known as closure type, which is declared (for the purposes of ADL) in the smallest block scope, class scope, or namespace scope that contains the lambda expression.
🌐
Joshdata
joshdata.me › lambda-expressions.html
Lambda Expressions: A Guide
In this example, there is a single argument x, the expression x + 1 is computed, and that expression is returned to the caller. It can be written shorter as a lambda expression in modern versions of many languages, including C++ (starting in C++11), C# (starting in C# 9.0), Java (since Java 8), Javascript (starting in ECMAScript 6), and Python (since around Python 2.2):
Find elsewhere
🌐
Medium
medium.com › @afinlay › lambda-expressions-in-java-python-c-c-8cdbca5a5e8b
Lambda Expressions in Java, Python, C#, C++ | by Adrian D. Finlay | Medium
May 1, 2018 - Lambda Expressions in Java, Python, C#, C++ No, Lambda Expressions are not as complicated as Church’s Lambda Calculus. No need to worry. Lambda Expressions are simply an expression of an anonymous …
🌐
Endjin
endjin.com › blog › 2022 › 04 › understanding-lambda-expressions-in-csharp
Understanding Lambda Expressions in C# | endjin
April 29, 2022 - Explore C# lambda expressions, a concise method for defining functions, with a focus on syntax and practical examples.
🌐
Open-std
open-std.org › jtc1 › sc22 › wg14 › www › docs › n2892.pdf pdf
Basic lambdas for C
We propose here a version of lambdas that provides most of the functionality · of existing approaches; in particular it covers the possibility to capture values (as by de- fault done by Objective C’s block extension) and to capture identifiers (as by gcc’s nested ... III. DESIGN CHOICES · III.1. Expression versus function definition
🌐
DEV Community
dev.to › sandordargo › lambda-expressions-in-c-4pj4
Lambda Expressions in C++ - DEV Community
September 4, 2020 - Lambda expressions are anonymous functions. They are small snippets of code that provide a better readability in most cases if they are not hidden into an enclosing class. By the way, in C++, those enclosing classes would be called functors ...
🌐
GeeksforGeeks
geeksforgeeks.org › c++ › generalized-lambda-expressions-c14
Generalized Lambda Expressions in C++14 - GeeksforGeeks
July 30, 2024 - They are basically snippets of code that can be nested inside other functions and even function call statements. By combining a lambda expression with the auto keyword these expressions can then be later used in the program.
🌐
Medium
rekerner.medium.com › generic-lambda-expressions-in-c-20-and-alternatives-3838b6d9be9f
C++20: New Generic Lambda Expression Syntax | by bob kerner | Medium
August 3, 2024 - Generally, a generic lambda might looks something like this: ... The auto keyword was re-introduced and repurposed to indicate that a parameter can take accept any type, as with standard templates. In fact, auto can now be used to specify an overload of types of sorts for template functions and lambda.
🌐
USACO Guide
usaco.guide › home › general › (optional) c++ - lambda expressions
(Optional) C++ - Lambda Expressions · USACO Guide
The parameters, return type, and function body are all pretty straightforward. In competitive programming contexts, we typically use the following capture types: ... The lambda's local scope is the scope where it is defined, not the scope where it is used.
🌐
C# Corner
c-sharpcorner.com › UploadFile › bd6c67 › lambda-expressions-in-C-Sharp
Lambda Expressions in C#
September 4, 2023 - C# Lambda expressions are how anonymous functions are created. Lambda expressions are anonymous functions that contain expressions or sequence of operators.
🌐
Quora
cstdspace.quora.com › How-do-we-write-and-use-lambda-functions-in-pure-C-indirectly-instead-of-C
How do we write and use lambda functions in pure C indirectly instead of C++? - C Programmers - Quora
Answer (1 of 3): There aren’t any lambdas in C, so you can’t. You can create a context structure, populate it, and give it as an argument to a callback function, but the syntax is grotty and it is not nicely handled for things that take callbacks don’t have a void* argument for that context.
🌐
W3Schools
w3schools.com › cpp › cpp_functions_lambda.asp
C++ Lambda Functions
C++ Examples C++ Real-Life Examples C++ Compiler C++ Exercises C++ Quiz C++ Code Challenges C++ Syllabus C++ Study Plan C++ Certificate ... A lambda function is a small, anonymous function you can write directly in your code.
🌐
SmartBear
smartbear.com › blog › c11-tutorial-lambda-expressions-the-nuts-and-bolts
C++11 Tutorial: Lambda Expressions — The Nuts and Bolts of Functional Programming
November 1, 2012 - One highlight of C++11 is lambda expressions: function-like blocks of executable statements that you can insert where normally a function call would appear. Lambdas are more compact, efficient, and secure than function objects.
🌐
Built In
builtin.com › software-engineering-perspectives › c-plus-plus-lambda
C++ Lambda Expressions Explained | Built In
C++ lambda expressions are a simple way to define an anonymous function object or functor in C++. It can improve readability when writing callback functions.