以下代码来自include/linux/typecheck.h
:
/*
* 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; \\ <---- Why here is a 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; \
})
1;
会有什么不同吗?另外,块如何“评估为1”?
答案 0 :(得分:1)
宏是一个语句表达式:https://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html
最终表达式的值是宏“返回”的值。
如果typecheck
不是x
,则type
宏会导致编译时警告。假设我宣布char *a
然后尝试typecheck(char, a)
并使用gcc -Wall
编译:
1.c: In function 'main':
1.c:5:21: warning: comparison of distinct pointer types lacks a cast [enabled by default]
(void)(&__dummy == &__dummy2); \
^
1.c:14:2: note: in expansion of macro 'typecheck'
typecheck(char, a);
^