Checking type of a variable by preprocessor directive
Is there a way to check the type of variable by preprocessor ?
Actually I want to do something like this ://test.c
int main(void)
{
TYPE a=6;
#if TYPE==int
printf("%d\n",a);
#elif TYPE==float
printf("%f\n",a);
#endif
}
Now I use i开发者_开发百科t as :
gcc -o test -D TYPE=float test.c
But it is not working. TYPE is always matching with int and giving result according to %d.
Please help me to solve this problem.Using a combination of techniques from the following links:
https://github.com/pfultz2/Cloak/wiki/C-Preprocessor-tricks,-tips,-and-idioms http://jhnet.co.uk/articles/cpp_magic
#define CAT(a, ...) a ## __VA_ARGS__
#define SECOND(a, b, ...) b
#define IS_PROBE(...) SECOND(__VA_ARGS__, 0)
#define PROBE() ~, 1
#define NOT(x) IS_PROBE(CAT(_NOT_, x))
#define _NOT_0 PROBE()
#define BOOL(x) NOT(NOT(x))
#define IF(c) _IF(BOOL(c))
#define _IF(c) CAT(_IF_,c)
#define _IF_0(...)
#define _IF_1(...) __VA_ARGS__
#define IS_PAREN(x) IS_PROBE(IS_PAREN_PROBE x)
#define IS_PAREN_PROBE(...) PROBE()
#define IS_INT(t) IS_PAREN( CAT(_IS_INT_,t) (()) )
#define _IS_INT_int(x) x
#define IS_FLOAT(t) IS_PAREN( CAT(_IS_FLOAT_,t) (()) )
#define _IS_FLOAT_float(x) x
#define TYPE float
int main(void)
{
TYPE a=6;
IF(IS_INT(TYPE))(
printf("%d\n",a);
)
IF(IS_FLOAT(TYPE))(
printf("%f\n",a);
)
}
You can even test it out at https://godbolt.org/ with the -E compiler option.
The preprocessor can't compare strings like that. See this FAQ. The way to do it is by #defining the options, and there is an example there to help you.
精彩评论