Macro Substitution

  看《C程序设计语言》(英文版)学到的两个用法。

  

  两个很简单的宏用法。

  #的用法: if, however, a parameter name is preceded by a # in the replacement text, the combination will be expanded into a quoted string with the parameter replaced by the actual argument.

#include <stdlib.h>

#define dprint(expr) printf(#expr " = %g\n", expr);

int main() {
    double x = 1.0, y = 2.0;

    dprint(x/y);

    return 0;
}

结果为 x/y = 0.5

#define dprint(expr) printf(#expr " = %g\n", expr);

When this is invoked, as in 

#define dprint(expr) printf(#expr " = %g\n", expr);

the macro is expanded into

printf("x/y" " = %g\n", x/y);

and the strings are concatenated, so the effect is 

printf("x/y = %g\n", x/y);

Within the actual argument, each " is replaced by \" and each \ by \\, so the result is a legal string constant.

 

##的用法: The preprocessor operator ## provides a way to concatenate actual arguments during macro expansion. If a paramter in the replacement text is a adjacent to a ##, the parameter is replaced by the actual argument, the ## and surrouding white space are removed, and the result is re-scanned. 

例如:

#include <stdio.h>
#include <stdlib.h>

#define paste(front, back) front ## back

int main() {
    int x, x1;
    x = 2, x1 = 3;

    printf("%d\n", paste(x, 1));

    return 0;
}

输出结果是3.

 

#define paste(front, back) front ## back

so paste(x, 1) creates the token x1.

 

转载于:https://www.cnblogs.com/tanhehe/p/3239832.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值