Monday, May 31, 2010

The token-pasting operator

The operator ## is a binary operator, and can appear in the replacement text of any macro. It joins its left and right operands together into a single token, and for this reason is commonly called the token-pasting operator. If the resulting text also contains a macro name, the preprocessor performs macro replacement on it. Whitespace characters that occur before and after the ## operator are removed along with the operator itself.

Usually, at least one of the operands is a macro parameter. In this case, the argument value is first substituted for the parameter, but the macro expansion itself is postponed until after token-pasting. An example:

    #define TEXT_A "Hello, world!"     #define msg(x) puts( TEXT_ ## x )     msg(A);

Regardless of whether the identifier A has been defined as a macro name, the preprocessor first substitutes the argument A for the parameter x, and then performs the token-pasting operation. The result of these two steps is the following line:

    puts( TEXT_A );

Now, because TEXT_A is a macro name, the subsequent macro replacement yields this statement:

    puts( "Hello, world!" );

If a macro parameter is an operand of the ## operator and a given macro invocation contains no argument for that parameter, then the preprocessor uses a placeholder to represent the empty string substituted for the parameter. The result of token pasting between such a placeholder and any token is that token. Token-pasting between two placeholders results in one placeholder. When all the token-pasting operations have been carried out, the preprocessor removes any remaining placeholders. Here is an example of a macro call with an empty argument:

    msg( );

This call expands to the following line:

    puts( TEXT_ );

If TEXT_ is not an identifier representing a string, the compiler will issue an error message.

The order of evaluation of the stringify and token-pasting operators # and ## is not specified. If the order matters, you can influence it by breaking a macro up into several macros.


Source: C in a Nutshell - O'Reilly Media

No comments:

Post a Comment