例解GNU C之表达式中的复合语句

http://blog.csdn.net/npy_lp/article/details/7015066

前言:计算机语言是编译器和程序员交流的依据和规范,GNU C是GCC特有的功能,在Linux内核中被广泛应用。

    帮助文档:http://gcc.gnu.org/onlinedocs/gcc-4.6.2/gcc/C-Extensions.html#C-Extensions

 

    在讲解新概念之前,先回顾一下在标准C中表达式和复合语句的概念,表达式指的是运算符和操作数的组合,而复合语句指的是由一个或多个被括在花括号里的语句构成的代码块。

    在GNU C中,允许用小括号括起来的复合语句出现在一个表达式中。

    举例,如清单1: 

  1. #include <stdio.h>  
  2.   
  3. int main(void)  
  4. {  
  5.     int a = ({ int b = 8;  
  6.         int c = 99;  
  7.         b + c;  
  8.         b + c - 10;  
  9.         });  
  10.   
  11.     printf("a = %d\n", a);  
  12.   
  13.     return 0;  
  14. }  

    例子输出结果: 

  1. a = 97  

    注意,例子中a的值是复合语句中最后一个语句的值,并且它的数据类型与最后一个语句的数据类型相匹配。

    这种特性(Statements and Declarations in Expressions)在Linux内核中常被用于宏的定义中。

    举例,如清单2: 

  1. /* linux-2.6.38.8/include/linux/kernel.h */  
  2. #define min(x, y) ({            \  
  3.     typeof(x) _min1 = (x);      \  
  4.     typeof(y) _min2 = (y);      \  
  5.     (void) (&_min1 == &_min2);  \  
  6.     _min1 < _min2 ? _min1 : _min2; })  
  7.   
  8. /* linux-2.6.38.8/include/linux/kernel.h * 
  9.  * min_not_zero - return the minimum that is _not_ zero, unless both are zero 
  10.  * @x: value1 
  11.  * @y: value2 
  12.  */  
  13. #define min_not_zero(x, y) ({       \  
  14.     typeof(x) __x = (x);        \  
  15.     typeof(y) __y = (y);        \  
  16.     __x == 0 ? __y : ((__y == 0) ? __x : min(__x, __y)); })  
  17.   
  18. #include <stdio.h>  
  19.   
  20. int main(void)  
  21. {  
  22.     printf("min_not_zero(4, 0) = %d\n", min_not_zero(4, 0));  
  23.       
  24.     printf("min_not_zero(\'\\0\', \'a\') = %c\n", min_not_zero('\0', 'a'));  
  25.   
  26.     return 0;  
  27. }  

    例子输出结果: 

  1. min_not_zero(4, 0) = 4  
  2. min_not_zero('\0''a') = a 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值