- 论坛徽章:
- 0
|
今天看代码时看到一个有趣的东东,就是linux内核也有min函数,但它的实现很是奇怪,先贴出来:
/*
* min()/max() macros that also do
* strict type-checking.. See the
* "unnecessary" pointer comparison.
*/
#define min(x,y) ({ typeof(x) _x = (x); typeof(y) _y = (y); (void) (&_x == &_y); _x _y ? _x : _y; })
#define max(x,y) ({ typeof(x) _x = (x); typeof(y) _y = (y); (void) (&_x == &_y); _x > _y ? _x : _y; })
其他都很平常,但中间(void) (&_x == &_y);比较奇怪,这句干嘛用的的呢?
查了下网发现:
(void) (&_x == &_y)这句话本身都执行程序来讲完全是 div:eq(0) > div:eq(3) > table:eq(2) > tbody:eq(0) > tr:eq(0) > td:eq(0) > div:eq(0) > #content:eq(0) > br:eq(18)" anchorType="previous" jQuery1251853974125="6">一句
废话,它的作用在于,本身我们无法做这样的操作typeof(_x)==typeof(_y),所以故意判断他们2个的地址指针是否相等,显然是不可能相等,但是如果_x和_y的类型不一样,其指针类型也会不一样,2个不一样的指针类型进行比较操作,会抛出一个编译警告。也就是说char *p; int *q; 然后p==q;,这个判断因为一个是char*一个是int*,会在编译时产生一个warning。巧妙就巧妙在这里。
转载
http://www.armfans.net/thread-1527-1-1.html
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u3/94145/showart_2048294.html |
|