How to stringify an expression in C

前端 未结 7 1352
刺人心
刺人心 2020-12-07 01:53

Is there a way to evaluate an expression before stringification in c?

example:

#define stringify(x)  #x
...
const char * thestring = stringify( 10 *          


        
7条回答
  •  死守一世寂寞
    2020-12-07 02:30

    You probably won't like the format in which the expression is going to be presented, yes, it is possible, but in a very eclectic way - you'd need to create a separate functional language that is being "run" by the preprocessor. The proof:

    $ cvs -d:pserver:anonymous@chaos-pp.cvs.sourceforge.net:/cvsroot/chaos-pp login 
    $ cvs -z3 -d:pserver:anonymous@chaos-pp.cvs.sourceforge.net:/cvsroot/chaos-pp co -P chaos-pp
    $ cvs -z3 -d:pserver:anonymous@chaos-pp.cvs.sourceforge.net:/cvsroot/chaos-pp co -P order-pp
    $ cd order-pp/example
    $ grep -A 6 'int main' fibonacci.c
    int main(void) {
       printf
         ("The 500th Fibonacci number is "
          ORDER_PP(8stringize(8to_lit(8fib(8nat(5,0,0)))))
          ".\n");
       return 0;
    }
    $ cpp -I../inc fibonacci.c 2>/dev/null | grep -A 6 'int main' 
    int main(void) {
       printf
         ("The 500th Fibonacci number is "
          "139423224561697880139724382870407283950070256587697307264108962948325571622863290691557658876222521294125"
          ".\n");
       return 0;
    }
    

    In this example we have newly-made preprocessor-run purely functional language being used to calculate 500th Fibonacci number and then stringize it to give to C compiler.

    Of course I very much doubt that this is something that you'd ever use in practice, and it is a very far stretched abuse of the preprocessor, but I consider it to be a very thought-provoking hack. (and yes, without the exotic theoretical twists like this one, it's not possible).

提交回复
热议问题