Blocks (C language extension)

 玩聚上看见 神啊,C 终于开始支持 closure 了,吓了一跳啊,我的天啊!

 

 

#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() {
	IntBlock mycounter = MakeCounter(5, 2);
	printf("First call: %d\n", mycounter());
	printf("Second call: %d\n", mycounter());
	printf("Third call: %d\n", mycounter());
 
	Block_release(mycounter);
 
	return 0;
}
/* Output:
	First call: 5
	Second call: 7
	Third call: 9
*/

 

Code Comments(117) Sat, 17 Oct 2009 03:03:44 +0800