Can we paste 3 tokens using the C preprocessor ## operator?

Viewed 190

It seems possible to define a macro to concatenate 3 token as:

#define concat3(a,b,c) a##b##c

do intermediary tokens such as the ones produced by a##b or b##c have to be valid preprocessor tokens or is it possible to paste concat3(.,.,.) successfully on all conforming implementations?(1)


(1) Many compilers support .. as a token for case ranges, which makes it a valid token, but the C Standard does not define this token, so would the concat3() macro fail on architectures that do not support it?

1 Answers

It looks to me like each intermediate token has to be valid or it's considered undefined behavior. The sections I quote below are from the C11 standard, but the language in C99 and the C20 draft seem to be the same.

Section 6.10.3.3 covers the actual interpretation of the ## operator and specifically refers to the preceding and following tokens being concatenated, that is, they are handled in pairs. Paragraph 3 is a little confusing in that it mentions placemarker replacements separately (that is, expansions of a function-like macro where an argument has no preprocessing tokens) and then specifies that "If the result is not a valid preprocessing token, the behavior is undefined". It's not clear if it's referring to the placemarker case or all concatenations.

However, section J.2 identifies "the result of the preprocessing operator ## is not a valid preprocessing token" as undefined behavior without condition, so I think that may serve to clarify my point above.

Also note that the standard states that the order of evaluation of ## operators is unspecified, so each possible combination of concatenations would have to be valid.

Related