美文网首页
小括号内联复合表达式

小括号内联复合表达式

作者: Charlie_Z | 来源:发表于2018-10-25 15:57 被阅读12次

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和内联函数的结合体,它最大的意义在于将代码整理分块,将同一个逻辑层级的代码包在一起。

值的注意的是: 返回值和代码块结束点必须在结尾

相关文章

网友评论

      本文标题:小括号内联复合表达式

      本文链接:https://www.haomeiwen.com/subject/twtctqtx.html