Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force processor to use result of expression before pasting

My code is

#define PASTE__(a, b) a##b
#define PASTE_(a, b)  PASTE__(a, b)
#define PASTE(a, b) PASTE_(a, b)

int main()
{
    PASTE(1, (1+3)/4);
    return 0;
}

I would LIKE to have the result be

int main()
{
    11;
    return 0;
}

Compilable link: http://coliru.stacked-crooked.com/a/b35ea3e35a1b56ae

I put in two levels of indirection suggested by How can I guarantee full macro expansion of a parameter before paste?.

But still I get a preprocessor error:

main.c:8:11: error: pasting "1" and "(" does not give a valid preprocessing token
     PASTE(1, (1+3)/4);
           ^
main.c:1:23: note: in definition of macro 'PASTE__'
 #define PASTE__(a, b) a##b
                       ^
main.c:3:21: note: in expansion of macro 'PASTE_'
 #define PASTE(a, b) PASTE_(a, b)
                     ^
main.c:8:5: note: in expansion of macro 'PASTE'
     PASTE(1, (1+3)/4);

How do I get the preprocessor to resolve the result of that expression before doing concatenation?

like image 826
Bob Avatar asked Sep 26 '22 09:09

Bob


1 Answers

It looks like you're trying to get the preprocessor to evaluate some simple mathematical operations and convert to the result. This is not possible without substantial extra macro infrastructure to perform the necessary math. The easiest way to get the needed infrastructure is probably to use BOOST_PP.

http://www.boost.org/doc/libs/1_59_0/libs/preprocessor/doc/index.html

You would need to modify your code so that macros are used to perform the math rather than operators. The line in question would look like:

PASTE(1, BOOST_PP_DIV(BOOST_PP_ADD(1,3),4));

Now the answer would come out as 11, and I assume that's what you're looking for.

like image 113
Charles Ofria Avatar answered Sep 29 '22 07:09

Charles Ofria