user2162550 user2162550 - 2 months ago 6
C Question

Stringification macro always adds a single space character

Given the following code that prints a string which is a stringification of two words:

#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), ...) */


The output is always
" port: 1 "
with a single space between the
"port"
and the
"1"
. Why is there always a single space there and is there a way to control the amount of spaces?

changing the amount of spaces in
PORT_INFO_MAC_2
macro between
port
and
portNum
doesn't change the output space amount.

EDIT

It seems that there are two cases, at the fist case the
port
and
portNum
are closest-
PORT_INFO_MAC_2(portNum) port:portNum
which then no space exist in the output between them. At the second case, in which any number of spaces exist in the macro between them, the amount of spaces in the output is always 1.
Is there any formal explanation for that? Is there any control over that?

Answer

Why is there always a single space there and is there a way to control the amount of spaces?

Because that's what the stringification operator is specified to do:

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; emphasis added)

Of course, if there is no whitespace at all between the preprocessing tokens, then none appears in the stringification.