Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Macro evaluation in c preprocessor

I'd like to do something like this:

#define NUM_ARGS() 2
#define MYMACRO0(...) "no args"
#define MYMACRO1(...) "one arg"
#define MYMACRO2(...) "two args"
#define MYMACRO(num,...) MYMACRO##num(__VA_ARGS__)
#define GENERATE(...) MYMACRO(NUM_ARGS(),__VA_ARGS__)

And I expected it to evaluate to "two args". But instead I have

MYMACRONUM_ARGS()(1,1)

Is there a way to do what I want (using visual c++) ?

P.S. Eventually I want to implement logger that dumps all of variables. The next code

int myInt = 7;
string myStr("Hello Galaxy!");
DUMP_VARS(myInt, myStr);

will produce log record "myInt = 7; myStr = Hello Galaxy!"

like image 802
sergeyz Avatar asked Sep 01 '25 02:09

sergeyz


1 Answers

You need another macro because macro expansion does not take place near # or ##:

#define NUM_ARGS() 2
#define MYMACRO0(...) "no args"
#define MYMACRO1(...) "one arg"
#define MYMACRO2(...) "two args"
#define MYMACRO_AUX(num,...) MYMACRO##num(__VA_ARGS__)
#define MYMACRO(num,...) MYMACRO_AUX(num, __VA_ARGS__)
#define GENERATE(...) MYMACRO(NUM_ARGS(),__VA_ARGS__)

#include <stdio.h>

int main(void)
{
    puts(GENERATE(0, 1));

    return 0;
}

If this is what you're trying to do, but complicated preprocessor tricks are not really safe, as others already said, don't do it unless you really have to.

like image 184
effeffe Avatar answered Sep 02 '25 16:09

effeffe