liveBook · Manning

Lambda

As explained in Modern C, Third Edition

An anonymous function is a function construct without a program-level name, provided by a C extension for embedding callable behavior in expressions or macros.

A lambda is an anonymous function construct: it supplies callable behavior without a program-level name. In the macro pattern shown here, a capture list reads values from the surrounding context, an empty parameter list follows, and a trailing () invokes the lambda immediately. section 18.4

Use these rules to read the construct:

  • Write captures inside [ ... ]; this is the part that can read surrounding variables. section 18.4
  • Specify a capture as an identifier, an equals sign, and an initializer; its semantics resemble auto type inference with const qualification. section 18.4
  • Call a no-argument lambda by placing () after its body; execution ends at the body’s end or at return. section 18.4
  • Treat anonymous functions as an extension to the C standard rather than portable standard-C syntax. section 18.5

Immediate lambda for swapping

A SWAP macro captures pointers to its two operands, then immediately invokes a lambda whose body exchanges the pointed-to values. The captures serve as the lambda’s effective inputs while the empty parameter list keeps the call argument-free. section 18.4

How Modern C, Third Edition covers it

How deep it goes
Explains capture syntax, inferred const semantics, immediate invocation, and termination, but does not develop broader lambda mechanics.
Examples
Uses SWAP expansions that capture operand addresses and exchange their pointed-to values.
What it assumes
Assumes familiarity with macros, expressions, surrounding scopes, and inferred declarations.
What you can do after
Build it from scratch as an immediately invoked lambda inside a generic macro.
How it connects
Connects lambdas with macros, compound expressions, type inference, and block closures.

Also explained in

Compare how 18 books explain lambda →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.