Search code examples
cc-preprocessorstringify

Stringification Parentheses Elimination


In c I have the following in an existing code base:

#define MYVAR (1)

As you can see this is conforming good practices in C by surrounding the #define with parenthesis (even though I know in this case it makes no difference since the value is not an expression). Regardless I would like to use this in stringification. when I do this:

#define STRINGIFY(x) #x
#define TO_STRING(x) STRINGIFY(x)

const char* mystring = TO_STRING(MYVAR) ;

The resultant string is "(1)". I'd like to eliminate the parentheses without doing the simple:

#define MYVAR 1

Is there anyway to eliminate parentheses during stringification in c?


Solution

  • Just use STRINGIFY x instead of STRINGIFY(x)

    #include <stdio.h>
    
    #define MYVAR 1
    
    #define STRINGIFY(x) #x
    #define TO_STRING(x) STRINGIFY x
    
    int main(void)
    {
        const char *mystring = TO_STRING(MYVAR);
    
        printf("%s\n", mystring);
        return 0;
    }
    

    TO_STRING(x) expands to STRINGIFY (1) when MYVAR is defined as (1)

    If MYVAR is defined as 1 without parentheses you get a compile time error.