Is it possible to process math calculation before stringify a macro?

452 Views Asked by At

I look through a lot of examples online about macro stringification but can't find something similar.

I currently have the definitions as below.

#define PIN_A (0+1)
#define PIN_B (0+2)
#define PIN_C (0+3)
#define str(x) #x
#define xstr(x) str(x)
#define PIN_DEF(x) { #x, xstr(PIN_ ## x) }

The output of

PIN_DEF(A)

will become

{ "A", "(0+1)" }

However, what I really need is

{ "A", "1" }

Is it even possible? :/

1

There are 1 best solutions below

0
H Walters On

Yes, it's possible.

#include <boost/preprocessor/arithmetic.hpp>
#define PIN_A BOOST_PP_ADD(0,1)
#define PIN_B BOOST_PP_ADD(0,2)
#define PIN_C BOOST_PP_ADD(0,3)
#define str(x) #x
#define xstr(x) str(x)
#define PIN_DEF(x) { #x, xstr(PIN_##x) }

PIN_DEF(A)

Keep in mind boost preprocessor's arithmetic macros saturate at 256.

Caveats

The preprocessor can also evaluate expressions, but the only means of doing so is to invoke preprocessor conditional directives (such as #if <expression>/#elif <expression>). You can make a useful expression evaluator out of this, with usage limitations, but it doesn't seem to fit this use case. Macro math needs to be adopted to macro usage (and essentially implemented from scratch), so operations must be implemented in terms of macro calls.