Is there a way to do
#define A f1();
#define A A f2(); // this is wrong
#define A A f3(); // this is wrong
...
#define A A fn(); // this is wrong
A
and then get
f1(); f2(); f3(); ... fn();
Is there a way to do
#define A f1();
#define A A f2(); // this is wrong
#define A A f3(); // this is wrong
...
#define A A fn(); // this is wrong
A
and then get
f1(); f2(); f3(); ... fn();
You could use the boost preprocessor library. It can iterate macros and much more:
http://www.boost.org/doc/libs/1_43_0/libs/preprocessor/doc/index.html
EDIT: I read your comment and will stay tuned for solutions easier than the following code ;-) :
#include <boost/preprocessor/repetition/repeat.hpp>
#define A(z, n, text) text ## n = 0;
BOOST_PP_REPEAT(3, A, int x)
which generates
int x0 = 0; int x1 = 0; int x2 = 0;
Note that this is not a strict solution as it does not define a macro that repeats another macro but repeats an already defined macro.
When you write
#define foo [something]
if an occurence of foo
is found in the [something]
, it is simply ignored.
So it seems you cannot do recursion with the preprocessor, and use ugly hacks like BOOST_REPEAT, which "teaches the preprocessor how to count" by listing ugly macros. What you are asking for is not simple to do without BOOST_REPEAT.
#define A f1();
...
#define TEMP_A A
#undef A
#define A TEMP_A f2();
#undef TEMP_A
...
Though I suggest that you consider doing it as:
#define A f1()
// Note the lack of the semicolon
...
#define TEMP_A
#undef A
#define A do { TEMP_A; f2(); } while (0)
#undef TEMP_A
Since that would both allow and force you to use semicolons correctly when you call the macros in code.
It gets more complicated if your functions are returning values and you want to access these values, but then you should investigate the use of the coma operator.
#define A (( TEMP_A, f2() ))
This would allow you to have A
return the value returned by f2()
after running TEMP_A
, which is f1()
. The double parenthesis make it so that if you do something silly like:
printf A;
it doesn't try to treat it as an an argument list and only as a single argument.