closures

 http://en.wikipedia.org/wiki/Blocks_(C_language_extension)

 

Blocks are a nonstandard extension added by Apple Inc. to the C, C++, and Objective-C programming languages that uses a lambda expression-like syntax to create closures within these languages.

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 use 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 immediately at any later time by calling it, using the same syntax that would be used for calling a function.

[edit] Examples

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

#include <stdio.h>
#include <Block.h>
typedef int (^IntBlock)();
 
IntBlock MakeCounter(int start, int increment) {
	__block int i = start;
 
	return Block_copy( ^ {
		int ret = i;
		i += increment;
		return ret;
	});
 
}
 
int main(void) {
	IntBlock mycounter = MakeCounter(5, 2);
	printf("First call: %d/n", mycounter());
	printf("Second call: %d/n", mycounter());
	printf("Third call: %d/n", mycounter());
 
	/* because it was copied, it must also be released */
	Block_release(mycounter);
 
	return 0;
}
/* Output:
	First call: 5
	Second call: 7
	Third call: 9
*/
个人感言: 该方法可以用于保存与内存中某一变量值。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值