GCC泛型宏

在JAVA和CPP这种OOP语言中,都有泛型类,在C语言可以用宏定义实现泛型函数。

main.c

 1 #include <stdio.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 int main(int argc, char **argv) 
 9 {
10     int a = 5;
11     int b = 8;
12     int c;
13     double d = 11.1;
14     double e =9.9;
15     double f;
16     c = min(a, b);
17     f = min(d, e);
18     printf("the int min is %d\n",c);
19     printf("the double min is %f\n",f);
20     return 0;
21 }

 

 

Line 3:typeof(x)表示获取x的类型。

Line 5:(void) (&_min1 == &_min2);在编译提示。

若不同类型指针做逻辑比较在编译过程会提示:warning: comparison of distinct pointer types lacks a cast

 

参考资料:《Android驱动开发与移植实战详解》

posted @ 2016-06-14 12:01  Kevin_Hwang  阅读(1111)  评论(0编辑  收藏  举报