Generate string with an expanded value at compile time

Advertisements

Consider the following example:

#include <stdio.h>

#define VAL 1
#define mkstr(t) "Expansion of t is " #t

int main(void){
    printf(mkstr(VAL)); // prints Expansion of t is VAL
}

DEMO

Is there a way to expand the supplied macro to make the string of the form Expansion of t is 1 at compile time without explicit formatting at runtime?

>Solution :

Macro replacement processes the # operator before it replaces argument names in the replacement string. To deal with this, use a second macro so that the argument names are replaced, and the # operator occurs in a macro processed after that:

#include <stdio.h>

#define VAL 1
#define Helper(t) "Expansion of t is " #t
#define mkstr(t) Helper(t)

int main(void){
    printf(mkstr(VAL) "\n"); // prints Expansion of t is VAL
}

Leave a ReplyCancel reply