零零社区|百姓的网上家园-互动交流平台!(0.0)=^_^=(00社区)

 找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
热搜: 活动 交友 discuz

学习园地:Linux系统内核中判断大小的宏

2013-4-5 16:18| 发布者: 123456000000| 查看: 10| 评论: 0

摘要: Min和Max宏: /** 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 ...
 

Min和Max宏:

/** 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; })/** ..and if you can't take the strict* types, you can specify>

不是感觉跟我们用的有些不一样啊:

(void) (&_x == &_y);

(void) (&_x == &_y)这句话本身都执行程序来讲完全是一句废话,它的作用在于,本身我们无法做这样的操作typeof(_x)==typeof(_y),所以故意判断他们2个的地址指针是否相等,显然是不可能相等,但是如果_x和_y的类型不一样,其指针类型也会不一样,2个不一样的指针类型进行比较操作,会抛出一个编译警告。也就是说char *p; int *q; 然后p==q;,这个判断因为一个是char*一个是int*,会在编译时产生一个warning。巧妙就巧妙在这里。

由于内核是很多开发着一起开发的,其中还有一些其他的实现,就跟我们平常用的一样:

#define min(a,b) (((a) < (b)) ? (a) : (b))

试想:

min(++a,++b) ==> ((++a)<(++b))?(++a):(++b)

是不是就有问题了,传入的参数被加了两次。


路过

雷人

握手

鲜花

鸡蛋

相关阅读

发表评论

最新评论

相关分类


Archiver|手机版|小黑屋|00社区

GMT+8, 2023-1-31 10:50 , Processed in 0.045233 second(s), 18 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

返回顶部