/*
* 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; \
})
/*
* Check at compile time that 'function' is a certain type, or is a pointer
* to that type (needs to use typedef for the function type.)
*/
#define typecheck_fn(type,function) \
({ typeof(type) __tmp = function; \
(void)__tmp; \
})
//以上标红两句妙用,利用GCC规则在编译过程中检测到类型不匹配时告警
#include
int f(int a)
{
return a;
}
int main()
{
int i = typecheck(int,i);//不告警
int j = typecheck(char,j);//编译时告警
typecheck_fn(int (*)(int),f);//不告警
typecheck_fn(void (*)(int),f);//编译时告警
return 0;
}
阅读(2854) | 评论(0) | 转发(0) |