字符串化运算符 (#)

数字符号或“字符串化”运算符 (#) 将宏参数转换为字符串字面量,而不扩展参数定义。 它只用于采用参数的宏。 如果它在宏定义中位于形式参数之前,则由宏调用传递的实际自变量将用引号引起来并被视为字符串。 字符串随后替换宏定义中的字符串化运算符和形参的组合的每个匹配项。

注意

不再支持对 ANSI C 标准的 Microsoft C(6.0 版和早期版本)扩展,该扩展之前扩展了出现在字符串和字符常量内的扩展的宏形式自变量。 应使用字符串化运算符 (#) 来重新编写依赖此扩展的代码。

在实参的第一个标记前且紧跟其最后一个标记的空格将被忽略。 在生成的字符串中,将自变量标记之间的所有空格减少到单一空格。 因此,如果注释出现在实参的两个标记之间,则将其减少为单个空格。 生成的字符串字面量自动与仅由空格分隔的任何相邻的字符串字面量连接。

此外,如果参数中包含的字符在字符串字面量中使用时通常需要转义序列,例如引号 (") 或反斜杠字符 (\),那么必要的转义反斜杠会自动插入到该字符的前面。

当与包含转义序列的字符串一起使用时,Microsoft C++ 字符串化运算符的行为不正确。 在这种情况下,编译器会生成编译器错误 C2017

示例

以下示例显示一个包含字符串化运算符的宏定义和一个调用该宏的主函数:

// stringizer.cpp
#include <stdio.h>
#define stringer( x ) printf_s( #x "\n" )
int main() {
   stringer( In quotes in the printf function call );
   stringer( "In quotes when printed to the screen" );
   stringer( "This: \"  prints an escaped double quote" );
}

在预处理期间扩展 stringer 宏,生成以下代码:

int main() {
   printf_s( "In quotes in the printf function call" "\n" );
   printf_s( "\"In quotes when printed to the screen\"" "\n" );
   printf_s( "\"This: \\\" prints an escaped double quote\"" "\n" );
}
In quotes in the printf function call
"In quotes when printed to the screen"
"This: \"  prints an escaped double quote"

以下示例说明如何扩展宏参数:

// stringizer_2.cpp
// compile with: /E
#define F abc
#define B def
#define FB(arg) #arg
#define FB1(arg) FB(arg)
FB(F B)
FB1(F B)

另请参阅

预处理器运算符