Can I add numbers with the C/C++ preprocessor?

user318904 picture user318904 · Aug 22, 2010 · Viewed 13.6k times · Source

For some base. Base 1 even. Some sort of complex substitution -ing.

Also, and of course, doing this is not a good idea in real life production code. I just asked out of curiosity.

Answer

James McNellis picture James McNellis · Aug 22, 2010

The preprocessor operates on preprocessing tokens and the only time that it evaluates numbers is during the evaluation of a #if or #elif directive. Other than that, numbers aren't really numbers during preprocessing; they are classified as preprocessing number tokens, which aren't actually numbers.

You could evaluate basic arithmetic using token concatenation:

#define ADD_0_0 0
#define ADD_0_1 1
#define ADD_1_0 1
#define ADD_1_1 2

#define ADD(x, y) ADD##_##x##_##y

ADD(1, 0) // expands to 1
ADD(1, 1) // expands to 2

Really, though, there's no reason to do this, and it would be silly to do so (you'd have to define a huge number of macros for it to be even remotely useful).

It would be more sensible to have a macro that expands to an integral constant expression that can be evaluated by the compiler:

#define ADD(x, y) ((x) + (y))

ADD(1, 1) // expands to ((1) + (1))

The compiler will be able to evaluate the 1 + 1 expression.