Hailiang Zhang
Hailiang Zhang

Reputation: 18870

How to check the value of a macro in C?

Basically I want to do the following:

#define TYPE float

int main()
{
  if (TYPE==float)...;
}

Of course it wont' work, and not sure how to achieve it.

Upvotes: 1

Views: 168

Answers (3)

Barmar
Barmar

Reputation: 780879

You can use the C preprocessor's stringification operator.

 #define xstr(s) str(s)
 #define str(s) #s

 if (strcmp(xstr(TYPE), "float") == 0) ...

For an explanation of this, see here

Upvotes: 7

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272487

If you're looking for a platform-independent mechanism, then there isn't one, basically.*

A feasible approach is something like this:

#if USE_FLOAT
#define TYPE float
#else
#define TYPE blah
#endif

...

int main() {
    if (USE_FLOAT) {
       ...
    }
}

However, as a general rule, you should avoid conditional compilation based on macros wherever possible.


* Well, it turns out there's @Barmar's slick solution, but I guess I'd argue that's a pretty heavyweight runtime check...

Upvotes: 7

Lily Ballard
Lily Ballard

Reputation: 185671

You can use __builtin_types_compatible_p() to tell if two types are compatible.

if (__builtin_types_compatible_p(TYPE, float)) ...;

This is supported by both GCC and Clang.

Upvotes: 2

Related Questions