细数linux内核里那些偏门的C语言语法(二)x... 与 #x

 
   

同样是在跟linux内核源码的时候,看到这样的宏定义

 

#define __stringify_1(x...) #x
#define __stringify(x...) __stringify_1(x)

x...是什么意思呢? #x又是什么意思?

 

#x是将x转换成字符串。

比如下面代码

 

printf(__stringify_1(hello) );

输出结果为 hello

 

那么x...又是什么意思呢?

表示支持其他符合输入。

 

 

比如

#define TOSTRING(x)  #x

printf(TOSTRING(hello, kk) );

编译报错

加上...后

#define TOSTRING(x...)  #x

printf(TOSTRING(hello, kk) );

编译通过

输出结果为

hello, kk

 

x...有一个用法

以前我的DEBUG错误打印宏是这样定义的

#define DEBUG_ERR(buf) printf("Error:"buf)
#define DEBUG_ERR_ARG(buf, ...) printf("Error:"buf, __VA_ARGS__)

将带参数和不带参数的分开,不然编译会报错

 

知道这个用法之后只需要一个函数搞定

#define DEBUG_ERR(buf...) printf("Error:"buf)
这样带没带参数都可以了

 

  #define DEBUG_ERR(buf...) printf("Error: "buf)
 
  int main()
  {
  
      int len = 100;
  
      DEBUG_ERR("len is out of range , len = %d\n", len);
 
 
     return 0;
  }

输出结果为

Error: len is out of range , len = 100

 

你可能感兴趣的:(linux相关,C语言)