简体   繁体   中英

# symbol in printf statement doesn't work

This code executes properly

#include<stdio.h>
#define JOIN(s1, s2) printf("%s=%s %s=%s \n", #s1, s1, #s2, s2);

int main()
{
    char *str1="India";
    char *str2="BIX";
    JOIN(str1, str2);
    return 0;
}

but this code doesn't execute

#include<stdio.h>

int main()
{
    char *str1="India";
    char *str2="BIX";
    printf("%s=%s %s=%s \n", #str1, str1, #str2, str2);
    return 0;
}

I just replaced the first the macro of first segment coding .. but it doesn't work

Using the #var feature to result in "var" is part of the preprocessor, so you can only use that as part of a macro.

If you wanted to continue using it, often people write a macro called STRINGIFY:

#define STRINGIFY(x) #x

In your case though, the best thing would probably be to just do the quoting yourself.

char *str1="India";
char *str2="BIX";

printf("%s=%s %s=%s \n", "str1", str1, "str2", str2);

This is preprocessor syntax, and can ONLY be used inside a macro definition ( #define.. ).

Your code is first run through a CPP, the C PreProcessor, which takes care of all #xxx.. syntax. The result of this is then passed to C compiler, which knows nothing about #xxxx.. syntax.

You can try it out yourself - instead of gcc , run cpp on your file and you can see the result of macro expansion.

remove # it work only for macro

try this

   int main()
   {
   char *str1="India";
   char *str2="BIX";
   printf("str1=%s str2=%s \n", str1, str2);
   return 0;
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM