Apple designed blocks with the explicit goal of making it easier to write programs for the Grand Central Dispatch threading architecture [1][2], although it is independent of that architecture and can be used in much the same way as closures in other languages. Apple has implemented blocks in Apple's own copy of the GCC sources and in the clang LLVM compiler front end. Language runtime library support for blocks is also available as part of the LLVM project.

Like function definitions, blocks can take arguments, and declare their own variables internally. Unlike ordinary C function definitions, their value can capture state from their surrounding context. A block definition produces an opaque value which contains both a reference to the code within the block and a snapshot of the current state of local stack variables at the time of its invocation. The block may be later invoked in the same manner as a function pointer. The block may be assigned to variables, passed to functions, and otherwise treated like a normal function pointer, although the application programmer (or the API) must mark the block with a special operator (Block_copy) if it's to be used outside the scope in which it was defined.

Given a block value, the code within the block can be executed at any later time by calling it, using the same syntax that would be used for calling a function.

Examples

A simple example capturing mutable state in the surrounding scope is an integer range iterator[3]: