加载中…
个人资料
liufeifei11
liufeifei11
  • 博客等级:
  • 博客积分:0
  • 博客访问:46,434
  • 关注人气:5
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
相关博文
推荐博文
正文 字体大小:

_ _VA_ARGS_ _

(2012-02-24 17:02:27)
标签:

杂谈

分类: linux程序
Variadic Macros: ... and _ _VA_ARGS_ _

Some functions, such as printf(), accept a variable number of arguments. The stdvar.h header file,provides tools for creating user-defined functions with a variable number of arguments. And C99 does the same thing for macros.Although not used in the standard, the word variadic has come into currency to label this facility. (However, the process that has added stringizing and variadic to the C vocabulary has not yet led to labeling functions or macros with a fixed number of arguments as fixadic functions and normadic macros.)

The idea is that the final argument in an argument list for a macro definition can be ellipses (that is, three periods)(省略号). If so, the predefined macro _ _VA_ARGS_ _ can be used in the substitution part to indicate what will be substituted for the ellipses. For example, consider this definition:

#define PR(...) printf(_ _VA_ARGS_ _)

Suppose you later invoke the macro like this:

PR("Howdy");

PR("weight = %d, shipping = $%.2f/n", wt, sp);

For the first invocation, _ _VA_ARGS_ _ expands to one argument:

"Howdy"

For the second invocation, it expands to three arguments:

"weight = %d, shipping = $%.2f/n", wt, sp

Thus, the resulting code is this:

printf("Howdy");

printf("weight = %d, shipping = $%.2f/n", wt, sp);

Listing 2 shows a slightly more ambitious example that uses string concatenation and the # operator:


// 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:

0

阅读 评论 收藏 转载 喜欢 打印举报/Report
  • 评论加载中,请稍候...
发评论

    发评论

    以上网友发言只代表其个人观点,不代表新浪网的观点或立场。

      

    新浪BLOG意见反馈留言板 电话:4000520066 提示音后按1键(按当地市话标准计费) 欢迎批评指正

    新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 会员注册 | 产品答疑

    新浪公司 版权所有