分类: C/C++
2007-11-14 17:24:19
< Day Day Up > |
Creating Strings from Macro Arguments: The # OperatorHere's a function-like macro: #define PSQR(X) printf("The square of X is %d.\n", ((X)*(X))); Suppose you used the macro like this: PSQR(8); Here's the output: The square of X is 64. Note that the X in the quoted string is treated as ordinary text, not as a token that can be replaced. Suppose you do want to include the macro argument in a string. ANSI C enables you to do that. Within the replacement part of a function-like macro, the # symbol becomes a preprocessing operator that converts tokens into strings. For example, say that x is a macro parameter, and then #x is that parameter name converted to the string "x". This process is called stringizing. [Listing 16.3]illustrates how this process works. Listing 16.3. The subst.c Program/* subst.c -- substitute in string */ #include Here's the output: The square of y is 25. The square of 2 + 4 is 36. In the first call to the macro, #x was replaced by "y", and in the second call #x was replaced by "2 + 4". ANSI C string concatenation then combined these strings with the other strings in the printf() statement to produce the final strings that were used. For example, the first invocation becomes this: printf("The square of " "y" " is %d.\n",((y)*(y))); Then string concatenation converts the three adjacent strings to one string: "The square of y is %d.\n" Preprocessor Glue: The ## OperatorLike the # operator, the ## operator can be used in the replacement section of a function-like macro. Additionally, it can be used in the replacement section of an object-like macro. The ## operator combines two tokens into a single token. For example, you could do this: #define XNAME(n) x ## n Then the macro XNAME(4) would expand to the following: x4 [Listing 16.4] uses this and another macro using ## to do a bit of token gluing. Listing 16.4. The glue.c Program// glue.c -- use the ## operator #include Here's the output: x1 = 14 x2 = 20 Note how the PRINT_XN() macro uses the # operator to combine strings and the ## operator to combine tokens into a new identifier. |
< Day Day Up > |