宏定义中的#,##操作符和... and _ _VA_ARGS_ _

1.#
假如希望在字符串中包含宏参数,ANSI C允许这样作,在类函数宏的替换部分,#符号用作一个预处理运算符,它可以把语言符号转化程字符串。例如,如果x是一个宏参量,那么#x可以把参数名转化成相应的字符串。该过程称为字符串化(stringizing).
#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.
第一次调用宏时使用“y”代替#x;第二次调用时用“2+4"代#x。
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;
}

"##"符号的作用是在可变参数的个数为0时,消除参数前面的逗号:

#define MY_PRINTF(fs, …) printf(fs, ##__VA_ARGS__)

我们这样调用:

MY_PRINTF(“Hello, World”);

等价于

printf(“Hello, World”);

另外"##"符号还能够去掉括号,但是我现在还不是很明白,为什么能够做到这一点:

?
1
2
3
4
5
#define ENUM_COTENTS(...)  __VA_ARGS__
#define ENUM_CONTENT_REMOVE_PARENTHESIS(a)  ENUM_COTENTS##a
#define DEFINE_ENUM(name)  enum name { ENUM_CONTENT_REMOVE_PARENTHESIS(ENUM_LIST) };
#define ENUM_LIST (Sunday=1,Monday=2)
DEFINE_ENUM(WeekDay)

3.可变宏 ...和_ _VA_ARGS_ _
实现思想就是宏定义中参数列表的最后一个参数为省略号(也就是三个点)。这样预定义宏_ _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)错误!

// variadic.c -- variadic macros

#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(这个是错误的例子。)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值