且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在C中对宏参数进行类型检查

更新时间:2023-12-01 08:51:16

gcc支持typeof

gcc supports typeof

例如来自Linux内核的typesafe min宏

e.g. a typesafe min macro taken from the linux kernel

#define min(x,y) ({ \
    typeof(x) _x = (x); \
    typeof(y) _y = (y); \
    (void) (&_x == &_y);        \
    _x < _y ? _x : _y; })

但是它不允许您比较两种类型.请注意,尽管指针比较会产生警告-您可以像这样进行类型检查(也可以从linux内核中进行)

but it doesn't allow you to compare two types. Note though the pointer comparison which Will generate a warning - you can do a typecheck like this (also from the linux kernel)

#define typecheck(type,x) \
({  type __dummy; \
    typeof(x) __dummy2; \
    (void)(&__dummy == &__dummy2); \
    1; \
})

大概您可以做类似的事情-即比较指向参数的指针.

Presumably you could do something similar - i.e. compare pointers to the arguments.