Chinaunix首页 | 论坛 | 博客
  • 博客访问: 980046
  • 博文数量: 184
  • 博客积分: 10030
  • 博客等级: 上将
  • 技术积分: 1532
  • 用 户 组: 普通用户
  • 注册时间: 2005-12-27 18:32
文章分类

全部博文(184)

文章存档

2009年(1)

2008年(63)

2007年(39)

2006年(79)

2005年(2)

我的朋友

分类: C/C++

2007-11-14 17:24:19

   < Day Day Up >   

Creating Strings from Macro Arguments: The # Operator

Here'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 

#define PSQR(x) printf("The square of " #x " is %d.\n",((x)*(x)))



int main(void)

{

    int y = 5;



    PSQR(y);

    PSQR(2 + 4);



    return 0;

}


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 ## Operator

Like 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 

#define XNAME(n) x ## n

#define PRINT_XN(n) printf("x" #n " = %d\n", x ## n);



int main(void)

{

    int XNAME(1) = 14;  // becomes int x1 = 14;

    int XNAME(2) = 20;  // becomes int x2 = 20;

    PRINT_XN(1);        // becomes printf("x1 = %d\n", x1);

    PRINT_XN(2);        // becomes printf("x2 = %d\n", x2);



    return 0;

}


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 >   
阅读(711) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~