C stringification: convert constant to integer

259 views Asked by At

I need to convert defined constants to their integer values so I came up with this macro (STR_TO_CONST) for doing so...

#define STRFY_VAL(s) #s
#define STRFY_KEY(s) STRFY_VAL(s)
#define STR_TO_CONST(s) atoi(STRFY_KEY(s))

It works, but I'm wondering if there are any potential problems with it as I've never encountered this macro before despite having searched considerably for something like it.

2

There are 2 answers

6
AudioBubble On

The reason you never encountered this is that it's utterly pointless, but let's explain by example. Say you have the following:

#define FINALANSWER 42

// ...

int x = 2 * STR_TO_CONST(FINALANSWER);

now, this is semantically no different from:

int x = 2 * FINALANSWER;

That's because preprocessor macros are ultimately just textual replacement happening before you actually compile. Therefore, FINALANSWER is just as good as an integer constant as 42 is.

Your "solution" to a non-existing problem just adds overhead in that it adds a new string constant to your code and an unnecessary function call as well.

0
chux - Reinstate Monica On

I'm wondering if there are any potential problems with it (?)

Yes. Using atoi() to initialize a global results in something like "error: initializer element is not constant"

int x = STR_TO_CONST(123);  // error
int y = 123; // no error

int main(void) {
  return x + y;
}

Hide warnings. Only 1 line generated a useful warning "warning: overflow in implicit constant conversion [-Woverflow]"

int main(void) {
  int a = STR_TO_CONST(123456789012345);  // no warning
  int b = 123456789012345;                 // warning
  return a + b;
}

Range issue. With 32-bit int, the below will likely exceed atoi() range resulting in undefined behavior with no warning.

int main(void) {
  long long z = STR_TO_CONST(123456789012345);
  return !z;
}