1、min 和 max
/*
* min()/max() macros that also do
* strict type-checking.. See the
* "unnecessary" pointer comparison.
*/
1 #define min(x,y) ({ /
2 typeof(x) _x = (x); /
3 typeof(y) _y = (y); /
4 (void) (&_x == &_y); /
5 _x < _y ? _x : _y; })
我曾经在面试的时候,有遇到过这个问题,我当时是这样写的
#define MIN(x, y) (x) < (y) ? (x) : (y)
当时做的时候还在想,这么简单的问题,还来考我,随着时间的流逝,当我看到kernel.h中的min(x, y)的实现后
才知道我之前面试不上的原因了,呵呵
当时没相到这种情况
MIN(++a,++b) ==> ((++a)<(++b))?(++a) : (++b)
a++和b++分别执行了2次,而且min的结果,也不对了。
现在的理解:
typeof()是用来得到x的类型,是GNU C对 ANSI C的扩展,为什么要加第2和3两行,是因为防止min(x, y)中的参数是表达式。
第4行,其实没有实际意义,为了做类型检查,代码本身是把两个参数的地址拿来比较是否相等,肯定不会相等,但是,当加了
这行代码,当你把两个不同类型的地址拿来比较,编译器会报警告,加void是语法需要
听有的同志说,在2、3行中加上const 会更好,可能吧
2、类型检查的代码,内核这样做的,看了后,不佩服不行啊,就跟看见美女,不得不回头一样。
/*
* Check at compile time that something is of a particular type.
* Always evaluates to 1 so you may use it easily in comparisons.
*/
#define typecheck(type,x) /
({ type __dummy; /
typeof(x) __dummy2; /
(void)(&__dummy == &__dummy2); /
1; /
})