# 用來把參數轉換成字符
-
#include <stdio.h>
-
-
#define FUN(X) (printf("%s=%d\n",#X,X)) /* #用來把參數轉換成字符 */
-
-
int test(int argc, char ** argv)
-
{
-
int a = 1;
-
int b = 2;
-
-
FUN(a);
-
FUN(b);
-
FUN(a+b);
-
-
return 0;
-
}
-
/** 程序輸出結果:
-
*******************************
-
a=1
-
b=2
-
a+b=3
-
*******************************
-
*/
-
2、## 把兩個語言符號組合成單個語言符號
-
#include <stdio.h>
-
-
#define XNAME(n) x##n /* ## 這個運算符把兩個語言符號組合成單個語言符號*/
-
#define PXN(n) printf("x"#n" = %d\n",x##n)
-
-
int main(int argc, char ** argv)
-
{
-
int XNAME(1) = 10886; /*宏展開就是:x1 = 10086*/
-
-
PXN(1); /*宏展開就是:printf("x1 = %d\n",x1) */
-
-
return 0;
-
}
-
-
/** 程序輸出結果:
-
*******************************
-
x1 = 10886
-
*******************************
-
*/
-
-
3、__VA_ARGS__ 和 ##__VA_ARGS__
-
#include "stdio.h"
-
-
#define DEBUG1(format, ...) do{ \
-
printf(format, __VA_ARGS__); \
-
\
-
} while(0)
-
-
#define DEBUG2(format, args...) do{ \
-
printf(format, ##args); \
-
\
-
} while(0)
-
-
#define DEBUG3(format, ...) do{ \
-
printf(format, ##__VA_ARGS__); \
-
\
-
} while(0)
-
-
int
-
main( int argc, char **argv)
-
{
-
printf("hello world.1 \n");
-
-
//DEBUG1("hello world.2\n");//錯誤 參數為零
-
DEBUG1( "hello world.2 %d %d\n", 1, 2);
-
-
DEBUG2( "hello world.3\n");
-
DEBUG2( "hello world.3 %d %d %d\n", 1, 2, 3);
-
-
DEBUG3( "hello world.4\n");
-
DEBUG3( "hello world.4 %d %d %d %d\n", 1, 2, 3, 4);
-
-
return 0;
-
}
應用:
-
#include "stdio.h"
-
-
#define DEBUG_ON
-
-
#ifdef DEBUG_ON
-
#define DEBUG(format, ...) do{ \
-
printf("File:%s, Line:%d, "format"", __FILE__, __LINE__, ##__VA_ARGS__); \
-
\
-
} while(0)
-
#else
-
#define DEBUG(format, ...)
-
#endif
-
-
-
int
-
main(int argc, char **argv)
-
{
-
-
DEBUG("hello world %d %d\n", 1, 2);
-
-
return 0;
-
}
-
-
/**程序輸出結果:
-
***********************************************************
-
File:E:\C Language\printf.c, Line:19, hello world 1 2
-
***********************************************************
-
*/
1、#用來把參數轉換成字符.
2、##這個運算符把兩個語言符號組合成單個語言符號
3、 __VA_ARGS__ 是一個可變參數的宏,實現思想就是宏定義中參數列表的最后一個參數為省略號(也就是三個點)。
4、##__VA_ARGS__ 宏前面加上##的作用在於,當可變參數的個數為0時,這里的##起到把前面多余的","去掉的作用,否則會編譯出錯。
5、注意宏定義連接符 \ 后面不要有任何操作,直接回車,下一行的前面可以有空格。
======================================================-=============================================
為更好了解C/C++中可變參數的知識,我從網上摘錄了兩篇文章,算是自己的一個總結。本篇主要是關於“## __VA_ARGS__”宏的介紹和使用。