Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Generate string with an expanded value at compile time

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading