Blocks
Blocks are a clang extension to C enabled with the -fblocks
flag, though they're more common in -- and therefore usually associated with -- Objective-C.
The type syntax is similar to function pointers: return_type(^)(arg_types)
. These are typically used in typedefs, such as
typedef int(^int_function_t)(int);
The full syntax for defining one is this:
^return_type (arg_type arg_name) {
body();
}
However, the return type can usually be inferred from the body of the block. If the return type is omitted and the argument list is (void)
, that can be omitted, too. For example:
int (^square)(int) = ^(int x) { return x * x; };
int (^randomNumber)(void) = ^{ return 4; };
NB: the trailing semicolon after the closing brace is necessary to end the declaration statement, and is not part of the block.
Blocks are called with the same syntax as function pointers.
If you need to capture a variable by reference, you must mark it with the __block
storage specifier. Otherwise, capture by value is implicit:
int x = 4;
__block int y = 4;
void (^printX)(void) = ^{ printf("%d\n", x); };
void (^printY)(void) = ^{ printf("%d\n", y); };
++x;
++y;
printX(); // prints '4'
printY(); // prints '5'