Search code examples
c++cmacrosstrcmp

Meaning of # symbol as argument in strcmp()


I came across this line of code in legacy code:

#define func(x,y)  if(strcmp(x,#y)==0)

Anyone have an idea of the purpose for the # symbol preceding y?


Solution

  • as mentioned in the comments, this seems like stringification in a c macro.

    here is a little example that uses your sample code:

    #define doif(x, y) \
        if(strcmp(x,#y)==0) { \
            printf("doing! %s\n",x); \
        }\
        else { \
            printf("not doing!\n"); \
        } 
    
    int main()
    {
        char x[] = "test";
    
        doif (x, test);
        doif (x, something);
    
        return 0;
    }
    

    the stringification operator actually pastes y variable as a string before the compilation stage