1

I want to make a macro to return the real part of a complex number (which will work with double, float and long double types). The GNU C extension __real__ seems to fit the bill (although it is not portable unfortunately). I am trying the following:

#include <complex.h>
#if defined(__real__)
#define MYREAL(z) (__real__ z)
#endif

However it seems that the __real__ extension is not defined as a usual macro, so the defined(__real__) test fails, even though it is available. Does anyone know how to test for the existence of __real__ to make a proper macro for this?

Also, if anyone knows of a portable way to do this, I'd be interested in that solution as well.

phuclv
  • 37,963
  • 15
  • 156
  • 475
vibe
  • 333
  • 1
  • 9
  • Where does `__real__` come from? Maybe that header defines an include-once guard. – tadman Dec 18 '20 at 05:04
  • [`creal()`](https://en.cppreference.com/w/c/numeric/complex/creal) should handle whatever you throw at it. – tadman Dec 18 '20 at 05:05
  • It's perhaps not a dup, but [this question](https://stackoverflow.com/q/54079257/1270789) says it cannot easily be done. – Ken Y-N Dec 18 '20 at 05:06
  • creal() is defined for double, there are other functions (crealf, creall) for float and long double – vibe Dec 18 '20 at 05:27

2 Answers2

4

Per manual:

To test for the availability of these features in conditional compilation, check for a predefined macro __GNUC__, which is always defined under GCC.

Hence:

#ifdef __GNUC__

#define MYREAL(z) (__real__(z))

#endif
selbie
  • 100,020
  • 15
  • 103
  • 173
3

Also, if anyone knows of a portable way to do this, I'd be interested in that solution as well.

That would be the creal() macro in <tgmath.h>, which works for all complex types.

Shawn
  • 47,241
  • 3
  • 26
  • 60