Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
357 views
in Technique[技术] by (71.8m points)

c - Check if a macro argument is a pointer or not

Is there some "nice" way to check if a variable passed to a macro is a pointer? e.g.

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

The idea is that this is not 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...