字符串化宏总是添加一个 space 字符
Stringification macro always adds a single space character
给定以下打印字符串的代码,该字符串是两个单词的字符串化:
#define PORT_INFO_MAC_2(portNum) port: portNum
#define PORT_INFO_MAC(portNum) PORT_INFO_MAC_2(portNum)
/* Stringify macro expansion instead of the macro itself */
#define INVOKE_MACRO(...) #__VA_ARGS__
printf(" %s " , INVOKE_MACRO(PORT_INFO_MAC(1)) ); /* In a more general way, I'll be using it like follows: INVOKE_MACRO(PORT_INFO_MAC(2), PORT_INFO_MAC(1), ...) */
输出总是 " port: 1 "
,在 "port"
和 "1"
之间有一个 space。为什么那里总是只有一个 space,有没有办法控制 space 的数量?
在 port
和 portNum
之间更改 PORT_INFO_MAC_2
宏中 space 的数量不会更改输出 space 数量。
编辑
似乎有两种情况,在第一种情况下,port
和 portNum
最接近 - PORT_INFO_MAC_2(portNum) port:portNum
然后它们之间的输出中不存在 space。在第二种情况下,它们之间的宏中存在任意数量的 space,输出中 space 的数量始终为 1。
对此有任何正式的解释吗?对此有任何控制吗?
Why is there always a single space there and is there a way to control the amount of spaces?
因为这就是指定字符串化运算符的目的:
If, in the replacement list, a parameter is immediately preceded by a #
preprocessing token, both are replaced by a single character string literal preprocessing token that contains the spelling of the preprocessing token sequence for the corresponding argument. Each occurrence of white space between the argument’s preprocessing tokens becomes a single space character in the character string literal.
(C2011 6.10.3.2/2;已强调)
当然,如果预处理标记之间根本没有空格,那么 none 会出现在字符串化中。
给定以下打印字符串的代码,该字符串是两个单词的字符串化:
#define PORT_INFO_MAC_2(portNum) port: portNum
#define PORT_INFO_MAC(portNum) PORT_INFO_MAC_2(portNum)
/* Stringify macro expansion instead of the macro itself */
#define INVOKE_MACRO(...) #__VA_ARGS__
printf(" %s " , INVOKE_MACRO(PORT_INFO_MAC(1)) ); /* In a more general way, I'll be using it like follows: INVOKE_MACRO(PORT_INFO_MAC(2), PORT_INFO_MAC(1), ...) */
输出总是 " port: 1 "
,在 "port"
和 "1"
之间有一个 space。为什么那里总是只有一个 space,有没有办法控制 space 的数量?
在 port
和 portNum
之间更改 PORT_INFO_MAC_2
宏中 space 的数量不会更改输出 space 数量。
编辑
似乎有两种情况,在第一种情况下,port
和 portNum
最接近 - PORT_INFO_MAC_2(portNum) port:portNum
然后它们之间的输出中不存在 space。在第二种情况下,它们之间的宏中存在任意数量的 space,输出中 space 的数量始终为 1。
对此有任何正式的解释吗?对此有任何控制吗?
Why is there always a single space there and is there a way to control the amount of spaces?
因为这就是指定字符串化运算符的目的:
If, in the replacement list, a parameter is immediately preceded by a
#
preprocessing token, both are replaced by a single character string literal preprocessing token that contains the spelling of the preprocessing token sequence for the corresponding argument. Each occurrence of white space between the argument’s preprocessing tokens becomes a single space character in the character string literal.
(C2011 6.10.3.2/2;已强调)
当然,如果预处理标记之间根本没有空格,那么 none 会出现在字符串化中。