Re: typecheck code

From: Jamie Iles
Date: Mon Jan 31 2011 - 12:20:51 EST


On Mon, Jan 31, 2011 at 12:03:37PM -0500, Sri Ram Vemulpali wrote:
> Hi all,
>
> /*
> * 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; \

So here we're creating __dummy of the macro specified type and __dummy2
by using the GCC extensions to work out the type.

> (void)(&__dummy == &__dummy2); \

This does a comparison and casts the result to void so we ignore the
result at runtime (and the compiler can optimise it away), but at
compile time, if the types don't match then we'll get:

warning: comparison of distinct pointer types lacks a cast

> 1; \

and here we always return 1.

> })
>
> #define typecheck_fn(type,function) \
> ({ typeof(type) __tmp = function; \
> (void)__tmp; \
> })
>
> Can anyone help me, explain the above code typecheck. How does
> (void)(&__dummy == &__dummy2) evaluates to 1

It's not that comparison that is evaluating to 1, it's the line
immediately after. The GCC statement expression extensions [1] mean
that the "1; \" at the end will always be the value that the macro is
evaluated to.

Jamie

1. http://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html
--
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at http://vger.kernel.org/majordomo-info.html
Please read the FAQ at http://www.tux.org/lkml/