# 宏定义中的‘#’、‘##’操作符和‘...’、‘ __变参__ ’

1.#

#incldue <stdio.h>
#define PSQR(x) printf("the square of" #x "is %d.\n",(x)*(x))
int main(void)
{
int y =4;
PSQR(y);
PSQR(2+4);
return 0;
}

the square of y is 16.
the square of 2+4 is 36.

2.##
##运算符可以使用类函数宏的替换部分。另外，##还可以用于类对象宏的替换部分。这个运算符把两个语言符号组合成单个语言符号。例如：
#define XNAME(n) x##n

XNAME(4)

x4

#include <stdio.h>
#define XNAME(x) x##4
#define PXN(n) printf("x"#n" = %d\n",x##n)
int main(void)
{
int XNAME(1)=12;//int x1=12;
PXN(1);//printf("x1 = %d\n", x1);
return 0;
}
3.可变宏 ...和_ _VA_ARGS_ _

#define PR(...) printf(_ _VA_ARGS_ _)
PR("hello");-->printf("hello");
PR("weight = %d, shipping = $.2f",wt,sp); -->printf("weight = %d, shipping =$.2f",wt,sp);

#define W(x,...,y)错误！

#include <stdio.h>

#include <math.h>

#define PR(X, ...) printf("Message" #X ": " _ _VA_ARGS_ _)

int main(void)

{

double x = 48;

double y;

y = sqrt(x);

PR(1, "x = %g\n", x);

PR(2, "x = %.2f, y = %.4f\n", x, y);

return 0;

}

In the first macro call, X has the value 1, so #X becomes "1". That makes the expansion look like this:

（#为参数加双引号。）

print("Message " "1" ": " "x = %g\n", x);

Then the four strings are concatenated, reducing the call to this:

print("Message 1: x = %g\n", x);

Here's the output:

Message 1: x = 48

Message 2: x = 48.00, y = 6.9282

Don't forget, the ellipses have to be the last macro argument:

#define WRONG(X, ..., Y) #X #_ _VA_ARGS_ _ #y（这个是错误的例子。）

• 本文已收录于以下专栏：

举报原因： 您举报文章：宏定义中的‘#’、‘##’操作符和‘...’、‘ __变参__ ’ 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)