How to stringify an expression in C

前端 未结 7 1359
刺人心
刺人心 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:11

    The C preprocessor cannot do that, so use snprintf instead:

    char *stringify(int n) {
       char *res = malloc(12);
       snprintf(res, 12, "%d", n);
       return res;
    }
    

    Usage

    const char *thestring = stringify(10 * 50);
    

    NB

    For simplicity's sake I've omitted error control and free.

提交回复
热议问题