liveBook · Manning

Closure

As explained in Modern C, Third Edition

A block closure is an anonymous function construct that can access variables from its surrounding context, subject to capture and modification rules.

A block closure is an anonymous function construct written as void^(void){ ... }. The ^ replaces a function name, and a following () invokes the closure immediately without arguments. section 18.4

Immediate SWAP operation

A SWAP macro can place its exchange logic inside a block closure, then call it immediately: void^(void){ /* exchange values */ }(). The closure can read variables from surrounding scopes, but modification requires specially marked variables. section 18.4

Key rules:

  • Read surrounding variables by default. section 18.4
  • Permit modification only for specially marked variables. section 18.4
  • Terminate at the body’s end or at a return statement. section 18.4

How Modern C, Third Edition covers it

How deep it goes
Explains syntax, invocation, surrounding access, and modification restrictions.
Examples
Demonstrates block-closure syntax through an immediately invoked SWAP macro.
What it assumes
Assumes familiarity with functions, macros, surrounding scopes, and compound expressions.
What you can do after
Build it from scratch as an immediately invoked anonymous operation inside a macro.
How it connects
Connects block closures with compound expressions, macros, anonymous functions, and C++ lambdas.

Also explained in

Compare how 20 books explain closure →

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.