Search code examples
cconstantsc99

Is there a way to init a C double with a const value based on a hex pattern?


I have a need to put an invalid hex pattern into a C-99 double value.

Unfortunately, this does not work (for obvious reasons):

const double invalid_double = 0x7ff0000000000001;

Neither does this (because the deref of the int const isn't know to be const apparently)

const uint64_t invalid_int = 0x7ff0000000000001;
const double invalid_double =  *(((double*)&invalid_int);

And union init does not seem to help much either (because u.d is not considered compile time const):

union {
  double d;
  uint64_t i;
} const u = { .i = 0x7ff0000000000001 };


const double invalid_double =  u.d;

Is there a way? I know invalid double are undefined behaviour and that I am walking into strange territory here. But, I have a special use case for this value.


Solution

  • Use compiler extensions, for example GCC has __builtin_nan and __builtin_nans functions for quiet and signaling NaN respectively.

    const double invalid_double = __builtin_nans("1");  // 0x7ff0000000000001
    

    It's not C99, but better to fail predictably if compiler doesn't support it, than fail unpredictably with some hacky solution.

    You could also define your own NaN macro, which uses this builtin function on GCC, but reverts to standard NAN macro for other compilers.