简体   繁体   中英

Understanding typecheck in linux kernel

The following code is found from 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; \
})

Does the 1; make any difference? Also, how can a block "evaluates to 1"?

The macro is a statement expression: https://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html

The value of the final expression is the value "returned" by the macro.

The typecheck macro causes a compile time warning if x is not of type . Let's say I declared char *a and then tried typecheck(char, a) and compiled with 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);
  ^

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM