Basic Blocks
Saturday, August 29th, 2009Now that Snow Leopard has shipped, the Blocks Programming Topics is available from developer.apple.com. Go have a read; it is a great primer for Blocks.
This post is focused solely on the core syntax of Blocks; declaring a block and calling a block.
Blocks are closures for C.
That is, a block is an anonymous inline collection of code that (Note: lexical scope means function or method or {}-surrounded collection of statements:
- has a typed argument list just like a function
- has an inferred or declared return type
- can capture state from the lexical scope within which it is defined
- can optionally modify the state of the lexical scope
- can share the potential for modification with other blocks defined within the same lexical scope
- can continue to share and modify state defined within the lexical scope [the stack frame] after the lexical scope [the stack frame] has been destroyed
Blocks is available in GCC and Clang as shipped with the Snow Leopard Xcode developer tools. The Blocks runtime is open source and can be found within LLVM’s compiler-rt subproject repository. Blocks have also been presented to the C standards working group as N1370: Apple’s Extensions to C (which also includes Garbage Collection).
As Objective-C and C++ are both derived from C, Blocks are designed to work fine with all three languages. Thus, the syntax reflects this goal.
A block is introduced using the ^ — the caret — character. The ^ was chosen as it had no unary form (and C++ couldn’t operator overload it).
For the purposes of an excruciatingly simple example, how about a block that multiplies two numbers?






