Search code examples
c++cmacrosstringify

Stringification of int in C/C++


The below code should output 100 to my knowledge of stringification. vstr(s) should be expanded with value of 100 then str(s) gets 100 and it should return the string "100". But, it outputs "a" instead. What is the reason? But, if I call with macro defined constant foo then it output "100". Why?

#include<stdio.h>
#define vstr(s) str(s)
#define str(s) #s
#define foo 100
int main()
{
    int a = 100;
    puts(vstr(a));
    puts(vstr(foo));
    return 0;
}

Solution

  • The reason is that preprocessors operate on tokens passed into them, not on values associated with those tokens.

    #include <stdio.h>
    
    #define vstr(s) str(s)
    #define str(s) #s
    
    int main()
    {
        puts(vstr(10+10));
        return 0;
    }
    

    Outputs: 10+10