X
X
xanep2013-08-10 06:21:07
C++ / C#
xanep, 2013-08-10 06:21:07

How to count and convert to string in C++ using preprocessor?

Tell me how in C ++ using macros, first calculate the formula, and convert the result to a string? For example, there is
#define A 2
#define B 3
#define MUL(x,y) (x*y)
#define STR(x) #x
How do I get the string "6"? Naturally STR(MUL(A,B)) doesn't work.

Answer the question

In order to leave comments, you need to log in

6 answer(s)
M
mayorovp, 2013-08-10
@xanep

No way - the preprocessor, in principle, does not perform arithmetic operations. Is it possible to stir up some lambda calculus ...

V
vScherba, 2013-08-10
@vScherba

Hm, why not?
#include <boost/preprocessor.hpp>
BOOST_PP_STRINGIZE(BOOST_PP_MUL(A, B))

I
ixSci, 2013-08-10
@ixSci

As you have already been pointed out above, macros are what follows from their name - macro substitution. What you want to achieve, in older editions of C++, is decided by templates. In the new one - constexpr.

A
Alexey Sidorov, 2013-08-10
@Gortauer87

The macros themselves don't evaluate, of course, but the value 3 + 3 is still calculated at compile time. That's just the line where 6 is written, you can't make it out of it.

C
coffeesmoke, 2015-07-09
@coffeesmoke

Choose what you need

#include <QtCore>
#include <iostream>

using namespace std;

# define MULT(VAL1,VAL2) ((VAL1)*(VAL2))
# define AS_STR(NUM_VAL) ( QString("")+#NUM_VAL )
# define AS_STR_VAL(NUM_VAL) ( QString().sprintf("%d",NUM_VAL) )


int main(int argc, char *argv[])
{
  QCoreApplication a(argc, argv);
  int i = MULT(1+2,1+1+1);
  cout << "Variant 1: " << qPrintable(AS_STR(i)) << endl;
  cout << "Variant 2: " << qPrintable(AS_STR(MULT(1+2,1+1+1))) << endl;
  cout << "Variant 3: " << qPrintable(AS_STR_VAL(MULT(1+2,1+1+1))) << endl;

  return a.exec();
}

Result (console):
Variant 1: i
Variant 2: MULT(1+2,1+1+1)
Variant 3: 9

S
Sergey Petrikov, 2014-10-13
@RicoX

Try adding the option:
option ip-forwarding on;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question