Search code examples
cmacrosdoublenotation

double scientific notation in macro


I was wondering if I can create macro that creating value with custom "shift" (or other way to create it in compile time). I mean, concatenate two numbers or something...

Something like that (of course it's not working):

#define CUSTOM_DOUBLE(shift) 1.05E shift

I know I can do:

#define CUSTOM_DOUBLE(shift) 1.05 * pow(10.0, shift)

But I'm aware that it isn't calculated in compile time.


Solution

  • As long as shift argument is passed as integer constant (of decimal form) this can be accomplished by ## operator, that concatenates preprocessing tokens. For instance, it may be implemented as:

    #include <stdio.h>
    
    #define CUSTOM_DOUBLE(shift) (1.05E ## shift)
    
    int main(void)
    {
        double d = CUSTOM_DOUBLE(3);
    
        printf("%E\n", d);
        return 0;
    }