Is there a way to detect whether a type is pointer in preprocessor of C?
Suppose its name is IS_POINTER. What the final result I want may looks like:
#define DATA_STRUCTURE(KEY_T)
#if IS_POINTER(KEY_T)
/* do something */
#endif
Thanks!
Is there a way to detect whether a type is pointer in preprocessor of C?
Suppose its name is IS_POINTER. What the final result I want may looks like:
#define DATA_STRUCTURE(KEY_T)
#if IS_POINTER(KEY_T)
/* do something */
#endif
Thanks!
The preprocessor has no notion of types, you cannot write such a macro that can be used in a #if
directive.
Conversely, you can use some non-portable built-in functions to write an expression that does check if a given object is a pointer or something else.
Here is a macro to perform a static assertion that a
is an array:
#define assert_array(a) \
(sizeof(char[1 - 2 * __builtin_types_compatible_p(typeof(a), typeof(&(a)[0]))]) - 1)
It can be used with gcc
and clang
. I use it to make the countof()
macro safer:
#define countof(a) ((ssize_t)(sizeof(a) / sizeof(*(a)) + assert_array(a)))
You could try using typeof(expr)
, which may help you in your task. It doesn't exactly tell you something is a pointer, but perhaps you could use it in comparisons: