C macro - checking if a variable is a pointer or n

2019-01-27 18:03发布

问题:

Just started thinking of this and was wondering if there's some "nice" way to check if a variable passed to a macro in c is a pointer? ie:

#define IS_PTR(x) something
int a;
#if IS_PTR(a)
printf("a pointer we have\n");
#else
printf("not a pointer we have\n");
#endif

The idea is not that this is done run-time but compile time, as in: we get different code depending on if the variable is a pointer or not. So i would like IS_PTR() to evaluate to some kind of constant expression in some way. Am i going about this idea all the wrong way?

Is this at all possible and how would it be done in that case? Thanks in advance!

回答1:

It is certainly not observable through the preprocessor in #if as you imply in your question. The preprocessor knows nothing about types, only tokens and expressions that are constructed from them.

C11 has a new feature that lets you observe a particular pointer type, but not "pointerness" in general. E.g you could do something

#define IS_TOTOP(X) _Generic((X), default: 0, struct toto*: 1)

or if you'd want that the macro also works for arrays

#define IS_TOTOPA(X) _Generic((X)+0, default: 0, struct toto*: 1)

There are already some compilers around that implement this, namely clang, and for gcc and others you can already emulate that feature with some builtins, see P99.



回答2:

NULL is pretty much the only thing you can look for. There is no way to determine if something is a pointer.