nalzok
nalzok

Reputation: 16117

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"?

Upvotes: 2

Views: 355

Answers (1)

dan4thewin
dan4thewin

Reputation: 1184

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);
  ^

Upvotes: 1

Related Questions