A compound statement enclosed in parentheses may appear as an expression in GNU C.
此用法来自gcc官方说明,源自gcc对c的扩展,如今被clang继承。
({ int y = foo (); int z;
if (y > 0) z = y;
else z = - y;
z; })
在iOS中可以这样使用:
UIButton *pop = ({
UIButton *button = [[UIButton alloc] initWithFrame: CGRectMake(160, 400, 120, 40)];
button.backgroundColor = [UIColor redColor];
[button setTitle: @"pop" forState: UIControlStateNormal];
[button addTarget: self action: @selector(popView) forControlEvents: UIControlEventTouchUpInside];
button;
});
有点像block和内联函数的结合体,它最大的意义在于将代码整理分块,将同一个逻辑层级的代码包在一起。
值的注意的是: 返回值和代码块结束点必须在结尾