2

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!

Lime
  • 71
  • 6
  • 1
    Wouldn't you know if it's a pointer or not since you wrote the code? I'm not sure I understand what you're really trying to accomplish. What is your goal in asking this question? – David Hoelzer Jun 19 '17 at 01:14
  • 1
    I don't think this is possible. The pre-processor knows very little about C and actually executes at a point in time where the C code isn't even parsed. Depending on what you are trying to achieve, you might have some luck with C11's [generic selection](http://en.cppreference.com/w/c/language/generic). – 5gon12eder Jun 19 '17 at 01:14
  • 1
    This sounds like an [XY Problem](http://mywiki.wooledge.org/XyProblem). Why would you need to know about this? What are you really trying to do? – Jonathan Leffler Jun 19 '17 at 01:16

2 Answers2

1

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)))
chqrlie
  • 131,814
  • 10
  • 121
  • 189
0

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:

https://gcc.gnu.org/onlinedocs/gcc/Typeof.html

Gerco Dries
  • 6,682
  • 1
  • 26
  • 35