先上代码:
int main()
{
int dmy = 256;
int val = 10;
const char *fmt = "val = %d\n";
void (^blk)(void) = ^{print(fmt, val)};
val = 2;
fmt = "These values were changed. val = %d\n";
blk();
return 0;
}
该代码中,Block语法的表达式使用的是它之前声明的自动变量fmt和val。Blocks中,Block表达式截获所使用的自动变量的值,即保存该自动变量的值,所以在执行Block语法后,即使改写Block中使用的自动变量的值也不会影响Blcok执行时自动变量的值。