Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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\n");
#else
printf("not a pointer we have\n");
#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?

like image 372
lfxgroove Avatar asked Oct 08 '13 18:10

lfxgroove


People also ask

Is type checking done in macro?

In macros, no type checking(incompatible operand, etc.) is done and thus use of macros can lead to errors/side-effects in some cases. However, this is not the case with functions. Also, macros do not check for compilation error (if any).

How to define macro functions in C?

To define a macro that uses arguments, you insert parameters between the pair of parentheses in the macro definition that make the macro function-like. The parameters must be valid C identifiers, separated by commas and optionally whitespace.

How to define macros in Cpp?

A macro is a piece of code in a program that is replaced by the value of the macro. Macro is defined by #define directive. Whenever a macro name is encountered by the compiler, it replaces the name with the definition of the macro. Macro definitions need not be terminated by a semi-colon(;).

What are Predefined macros in c language?

Predefined Macros in C99 standard: __cplusplus: __cplusplus Macro is defined when the C++ compiler is used. It is used to test whether a header is compiled by a C compiler or a C++ compiler. This macro gives value similar to __STDC_VERSION__, in that it expands to a version number.


1 Answers

On Clang and GCC, __builtin_classify_type(P) evaluates to 5 if P is an object with a pointer type.

like image 167
zneak Avatar answered Sep 28 '22 16:09

zneak