Lably
Skip to content

Blocks (C language extension)

Extension to the C programming language

  • 5 min read
  • 4 chapters

Related on Lably

Through Integer and Scope (computer programming)

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 definition. 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.

Blocks were originally introduced in 2009 with the explicit goal of making it easier to write programs for the Grand Central Dispatch (libdispatch) threading architecture. It does not, however, rely on libdispatch; instead it depends on its own (much simpler) runtime library to work. A blocks runtime library is preinstalled for Mac OS X 10.6+ and iOS 4.0+.

Scope of support

There are only two families of compilers that implement blocks: Apple's own branch of the GNU Compiler Collection (Apple GCC 4.2.1 and LLVM-GCC) and the upstream Clang LLVM compiler front end. Apple GCC is abandoned since circa 2011 (XCode 4.2). The most up-to-date description of this language extension is found in Clang documentation.

As mentioned above, Apple operating systems released after 2009 have a built-in blocks runtime. The LLVM project provides a "target-independent" runtime that should work for every operating system supported by LLVM.

Sign in to keep reading

3 more chapters are free with a Lably account.

More in Computing and communication