Linux系统内核中判断大小的宏

上一篇 / 下一篇  2008-03-12 17:00:00 / 个人分类:技术摘录

 

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 one yourself.
*
* Or not use min/max at all, of course.
*/
#define min_t(type,x,y) \
({ type __x = (x); type __y = (y); __x < __y ? __x: __y; })
#define max_t(type,x,y) \
({ type __x = (x); type __y = (y); __x > __y ? __x: __y; })

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

(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)

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


TAG:

 

评分:0

我来说两句

显示全部

:loveliness: :handshake :victory: :funk: :time: :kiss: :call: :hug: :lol :'( :Q :L ;P :$ :P :o :@ :D :( :)

日历

« 2008-09-06  
 123456
78910111213
14151617181920
21222324252627
282930    

数据统计

  • 访问量: 4813
  • 日志数: 229
  • 建立时间: 2007-08-01
  • 更新时间: 2008-08-20

RSS订阅

Open Toolbar