宏在C语言中的使用

宏在C语言中的使用,c,c-strings,C,C Strings,我试图生成一个双引号输入的输出。例如,如果str()中传递的参数是某个名称,那么输出应该是“name”,这在下面的代码中不会发生 #include<stdio.h> #include<string.h> #define str(s) #s #define newline printf("\n") int main() { printf("Your double quoted code is : %s ",str(GHOST)); newline; } #包

我试图生成一个双引号输入的输出。例如,如果str()中传递的参数是某个名称,那么输出应该是“name”,这在下面的代码中不会发生

#include<stdio.h>
#include<string.h>
#define str(s) #s
#define newline printf("\n")

int main()

{

  printf("Your double quoted code is : %s ",str(GHOST));
  newline;
}
#包括
#包括
#定义str(s)#s
#定义换行printf(“\n”)
int main()
{
printf(“您的双引号代码是:%s”,str(GHOST));
新线;
}
输出:GHOST


您应该将格式编辑为
\“%s\”

现在发生的是添加了引号,但它们作为语言语法的一部分使用。因为,您需要将类似于
“GHOST”
的字符串传递给
printf
,而不仅仅是一个标识符

如果您希望在运行程序时显示引号,我会让它

printf("Your double quoted code is : \"%s\" ",str(GHOST));

相反。格式字符串中的转义引号将出现在输出中。

这应该可以做到

printf("Your double quoted code is : \"%s\"",str(GHOST));

可以对字符串应用stringify运算符:

#define xstr(x) #x
#define str(x) xstr(x)
#define quote(x) str(str(x))

int main() {
  printf("Your double quoted code is : %s ",quote(GHOST));
  putchar('\n');
  return 0;
}

但是,使用
xstr
将参数重新扫描为
str
——内部
str(GHOST)
展开所必需的副作用是,如果
GHOST
本身是一个宏定义,它将被展开,与问题中代码片段中的“重影”不同。

如果要在输出中使用双引号字符,请将格式字符串更改为

printf("Your double quoted code is : \"%s\" ",str(GHOST));
或者将宏更改为

#define str(s) "\"" #s "\""

我建议不要以这种方式使用宏,但你问了这个问题。

这几乎是我见过的最不规则的C代码。(不包括混淆/代码高尔夫比赛)请不要这样写代码。我建议在您理解语言本身之前不要使用宏定义。只是一个建议。