0

I have a question about C preprocessor. I have define the macros:

#define num2str(x)      str(x)

#define str(x) #x

and I pass a number to a string constant:

const   char    myString[]     = num2str(NUMBER);

When I put for example #define NUMBER 10 works fine. But I want to put num2str(NUMBER + 10), and the result is "10 + 10" instead of "20". Is there any way to evaluate the expression NUMBER+10 and obtain "20"?

2
  • 2
    Is there *any* way.. Use something else then C preprocessor. Like m4. Commented Jul 16, 2021 at 11:59
  • While the C preprocessor does have the capability to evaluate certain simple constant expressions, those results are only usable in preprocessor expressions such as #if expressions. I don't know of a way to actually have the evaluated results placed into the preprocessor output. Commented Jul 16, 2021 at 12:05

2 Answers 2

1

In C, macro replacement does not do arithmetic.

There are some kludges that can implement limited arithmetic. Determining whether such a kludge would serve your purpose requires further information about your problem.

Sign up to request clarification or add additional context in comments.

Comments

1

Macros are text substitutions1, nothing more. Macro arguments are not evaluated, they are simply expanded in place.


  1. Strictly speaking they’re token substitutions, but the distinction is pretty minor in this case.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.