0

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.

Popiel
  • 183
  • 3
  • 13

2 Answers2

3

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;
}
Grzegorz Szpetkowski
  • 36,988
  • 6
  • 90
  • 137
2

You want this:

#define CUSTOM_DOUBLE(shift) 1.05E##shift

## is the concatenation operator.

Community
  • 1
  • 1
Emil Laine
  • 41,598
  • 9
  • 101
  • 157