| ▲ | sltkr 5 hours ago | ||||||||||||||||||||||
For the non-capturing case: mainly to improve readability by allowing utility functions to be defined close to where they are used and with short names. For the capturing case: to access context that is not available through global variables or function arguments, i.e., the same reason why closures are useful in other languages. Here's an example, where I have a list of points that I want to sort based on distance to a chosen target point. I can use qsort() which takes an arbitrary comparison function, but has no way to provide context to that function beyond the input arguments:
Note here that dsq() is a local function that accesses the `target` variable in the local function scope.The usual workaround in standard C is to pass the necessary context as a function argument. That's why qsort_r() exists, which takes a context argument to be passed to compare(), but that's a non-standard GNU extension. This practice of passing context pointers around is ubiquitous in C code, and it works, but it can get messy especially if you need access to multiple variables or variables from more than one nested scope. There is also a type safety issue: these context pointers are necessarily passed as void* which means they have to be cast back to the real type before use, which is where bugs can be introduced if the caller and receiver disagree on the actual type. | |||||||||||||||||||||||
| ▲ | uecker 3 hours ago | parent [-] | ||||||||||||||||||||||
This is a good example. Without trampolines, this could look like this (Godbolt: https://godbolt.org/z/nK5fqMxjs).
There are slightly different ways how to define the helper macros, I am still experimenting a bit. Here you could avoid the typedef if defined differently. But ideally, there would be native language support that avoids these macros. | |||||||||||||||||||||||
| |||||||||||||||||||||||