找回密码
 立即注册

扫一扫,访问微社区

QQ登录

只需一步,快速开始

搜索
热搜: 活动 交友 discuz
查看: 1778|回复: 0

宏定义中的特殊参数(#、##、...和__VA_ARGS__)

[复制链接]

96

主题

6

回帖

108

积分

屌炸天

积分
108
发表于 2017-7-4 16:28:32 | 显示全部楼层 |阅读模式

[转自] http://blog.csdn.net/cqupt_chen/article/details/8055215

最近在Android的某个代码的头文件中发现很多__VA_ARGS__,google一下.还是比较有用.附带其它宏定义参数,一起记录之.
1.    ...和__VA_ARGS__
看看msdn上给得例子吧

[cpp] view plain copy
print?

  • #include <stdio.h>
  • #define EMPTY
  • #define CHECK1(x, ...) if (!(x)) { printf(__VA_ARGS__); }
  • #define CHECK2(x, ...) if ((x)) { printf(__VA_ARGS__); }
  • #define CHECK3(...) { printf(__VA_ARGS__); }
  • #define MACRO(s, ...) printf(s, __VA_ARGS__)
  • int main() {
  •     CHECK1(0, "here %s %s %s", "are", "some", "varargs1(1)\n");
  •     CHECK1(1, "here %s %s %s", "are", "some", "varargs1(2)\n");   // won't print
  •     CHECK2(0, "here %s %s %s", "are", "some", "varargs2(3)\n");   // won't print
  •     CHECK2(1, "here %s %s %s", "are", "some", "varargs2(4)\n");
  •     // always invokes printf in the macro
  •     CHECK3("here %s %s %s", "are", "some", "varargs3(5)\n");
  •     MACRO("hello, world\n");
  •     // MACRO("error\n", EMPTY);   would cause C2059
  • }


我们看看输出:
here are some varargs1(1)
here are some varargs2(4)
here are some varargs3(5)
hello, world
是不是很有趣,以后我们如果在一些情况下要定义自己的打印函数就特别方便了
比如我们要在A条件成立,且B条件不成立的情况下打印输出
可以做如下定义:

[cpp] view plain copy
print?

  • #define CHECK1(A,B,...) if ((A)&&!(B)) { printf(__VA_ARGS__); }


记住一点...只能代替后面的参数,如下定义可行不通:

[cpp] view plain copy
print?

  • #define W(x,...,y)


是不是很像C++的函数的默认参数一样.


2.   #
这个特殊的宏定义参数也特别有用.#作为一个预处理运算符,它可以把语言符号字符串化(stringizing).例如我们定义的变量等.
看一个简单的例子:

[cpp] view plain copy
print?

  • #include <stdio.h>
  • #define TEST(x) printf("square of  " #x " is %d.\n",(x)*(x))
  • void main()
  • {
  •     int y =4;
  •     TEST(y);
  •     TEST(6-3);
  •     TEST(y+3);
  • }



输出结果:

[cpp] view plain copy
print?

  • square of  y is 16.
  • square of  6-3 is 9.
  • square of  y+3 is 49.


3.   ##
##运算符可以用于类函数宏的替换部分.##还可以用于类对象宏的替换部分.这个运算符可以把两个语言符号组合成单个语言符号.

例如:

[cpp] view plain copy
print?

  • #define XNAME(n) x##n
  • 执行宏调用:
  • int XNAME(4)
  • 展开后:
  • x4;//相当于直接定义 int x4 这里也就体现了两个语言符号的拼接.不过在android经常看到有关##拼接语言符号的情况.







您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|Comsenz Inc. ( 粤ICP备15088888号-2 )

GMT+8, 2024-4-26 13:17 , Processed in 0.102022 second(s), 10 queries , File On.

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表