0

Consider the following code:

1. #define SUFFIX 5-5
2. #define XFUNC_0( x )  (100 * x)
3. #define XFUNC_1( x )  (101 * x)
4. #define XFUNC_2( x )  (102 * x)
5. #define CATX( x, y )  x##y
6. #define CAT( x, y )   CATX( x, y )
7. #define XFUNC         CAT( XFUNC_, SUFFIX )
8. #if     XFUNC(2) == 200
...... etc
N. #endif

This code does not seem very useful, this is because it is just a part of my real code, simplified. The question is: - how can I convince the preprocessor to perform first 5-5 (just an example of a math operation) and the result (in this example, zero) to be concatenated to XFUNC_? As it is now it does not work, it tells me "unexpected tokens following preprocessor directive - expected a newline", at line 8. update: It seems right, the above code will be simple code replacement with the result XFUNC_5-5. But in this case I have another question: - does exist a way to have a function like macro or something which accepts as input(parameter) an expresssion and outputs a number; I think maybe something like a vector where you put consecutive numbers: you put the index (which could be an entire expresion) and you get as result the same, except that now is not expression but "pure" number which could be then concatenated

pssp
  • 1
  • 2
  • 3
    Short answer: you can't. If you explain what are *really* trying to with this whole mess of macros there is probably a much better way than abusing the preprocessor like this. – Paul R May 21 '12 at 13:09
  • related: http://stackoverflow.com/questions/1560357/can-the-c-preprocessor-perform-integer-arithmetic – Nate Kohl May 21 '12 at 13:11

3 Answers3

6

You can't. The preprocessor will do simple text replacement before passing the file to the compiler. It will not perform calculations.

harald
  • 5,976
  • 1
  • 24
  • 41
  • 1
    It looks like the preprocessor actually can perform calculations, for example when evaluating `#if` conditions. But that probably still isn't helpful here. – Nate Kohl May 21 '12 at 13:15
  • Nate, you are of course right, but then just to evaluate the expression in the conditional. – harald May 21 '12 at 13:19
1

P99 implements preprocessor arithmetic for modestly sized integers.

Jens Gustedt
  • 76,821
  • 6
  • 102
  • 177
0

The macro will be expanded as XFUNC_5-5 as the preprocessor does a simple text replacement. Since this contains the character - you are getting the error.

Naveen
  • 74,600
  • 47
  • 176
  • 233