Jonny0201
Jonny0201

Reputation: 463

Is there any way to concatenate macro arguments when condition is true?

I want to concatenate the macro arguments when condition is true :

#define concat(x, y) (x##y)
#define concat_if(cond, x, y) (((cond) > 0) ? concat(x, y) : (x))

For example,

int concat_if(1, hello, 0);    //int hello0;
int concat_if(0, hello, 1);    //int hello;

But this will make compile-error (Clang) :

error: use of undeclared identifier 'hello0'
    int concat_if(1, hello, 0);
        ^ note: expanded from macro 'concat_if'
#define concat_if(cond, x, y) (((cond) > 0) ? concat(x, y) : (x))
                                              ^ note: expanded from macro 'concat'
#define concat(x, y) (x##y)
                      ^
<scratch space>:303:1: note: expanded from here
hello0
^
error: use of undeclared identifier 'hello'
    int concat_if(1, hello, 0);
                     ^
2 errors generated.

Upvotes: 1

Views: 261

Answers (2)

Qaz
Qaz

Reputation: 61920

With Boost.PP:

#include <boost/preprocessor.hpp>

#define concat_if(cond, x, y) BOOST_PP_IF(cond, BOOST_PP_CAT(x, y), (x))

int concat_if(1, hello, 0);    //int hello0;
int concat_if(0, hello, 1);    //int (hello);

From scratch, it's easy to emulate what Boost does:

#define concat(x, y) concat_i(x, y)
#define concat_i(x, y) x##y

#define concat_if(cond, x, y) concat(concat_if_, cond)(x, y)
#define concat_if_0(x, y) (x)
#define concat_if_1(x, y) concat(x, y)

int concat_if(1, hello, 0);    //int hello0;
int concat_if(0, hello, 1);    //int (hello);

The condition is appended to a helper macro prefix and separate macros are defined for either result. Note that I'd recommend making all of these macros FULL_UPPERCASE.

Upvotes: 4

R Sahu
R Sahu

Reputation: 206627

If you just pre-process

int main()
{
   int concat_if(1, hello, 0);    //int hello0;
   int concat_if(0, hello, 1);    //int hello;
}

you get

int main()
{
   int (((1) > 0) ? (hello0) : (hello));
   int (((0) > 0) ? (hello1) : (hello));
}

As you can see, the compiler has to process all those tokens. Those lines are syntactically invalid since the conditional expressions are, well, expressions. The need to be evaluatable.

In other words, using the conditional operator to declare variables of different names is not a viable strategy.

I am not able to suggest anything to solve your problem since I don't understand what the real problem is. It feels like an XY Problem at the moment.

Upvotes: 0

Related Questions