Macro to stringify the result of an arithmetic expression

452 views Asked by At

Is it possible to write a preprocessor macro which stringifies the result of an integer arithmetic expression in clang?

For example:

#define WIDTH 20
#define HEIGHT 30

int main()
{
    puts("The total area is " INT_TO_STRING(WIDTH*HEIGHT));
}

I know it's possible to do in Visual C++, using its __if_exists built-in macro. Here is the Visual C++ implementation:

#define STRINGIZE_(n) #n
#define STRINGIZE(n) STRINGIZE_(n)

template<bool> struct static_if_t;
template<> struct static_if_t<true> {};
#define static_if(c) __if_exists(static_if_t<(c)>)

template<int N> struct Abs { enum { n = N < 0 ? -N : N }; };

#define INT_TO_STRING(value) \
    static_if ((value)<0) {"-"} \
    UINT_TO_STRING(Abs<(value)>::n)

#define UINT_TO_STRING(value) \
    static_if ((value)>=1000000000) {INT_TO_STRING_HELPER((value),1000000000)} \
    static_if ((value)>=100000000)  {INT_TO_STRING_HELPER((value),100000000)} \
    static_if ((value)>=10000000)   {INT_TO_STRING_HELPER((value),10000000)} \
    static_if ((value)>=1000000)    {INT_TO_STRING_HELPER((value),1000000)} \
    static_if ((value)>=100000)     {INT_TO_STRING_HELPER((value),100000)} \
    static_if ((value)>=10000)      {INT_TO_STRING_HELPER((value),10000)} \
    static_if ((value)>=1000)       {INT_TO_STRING_HELPER((value),1000)} \
    static_if ((value)>=100)        {INT_TO_STRING_HELPER((value),100)} \
    static_if ((value)>=10)         {INT_TO_STRING_HELPER((value),10)} \
                                     INT_TO_STRING_HELPER((value),1)

#define INT_TO_STRING_HELPER(value,place) \
    static_if ((value)/place%10==0) {"0"} \
    static_if ((value)/place%10==1) {"1"} \
    static_if ((value)/place%10==2) {"2"} \
    static_if ((value)/place%10==3) {"3"} \
    static_if ((value)/place%10==4) {"4"} \
    static_if ((value)/place%10==5) {"5"} \
    static_if ((value)/place%10==6) {"6"} \
    static_if ((value)/place%10==7) {"7"} \
    static_if ((value)/place%10==8) {"8"} \
    static_if ((value)/place%10==9) {"9"}

Can it be done in clang?

0

There are 0 answers