为什么在内核中碰到很多 #defines ... do{ ... } while(0)?

有以下几点原因:

1.当宏里面有if时,可以起到封闭代码作用,防止与外面的 if 混淆

  比如定义宏,#define FREE1(p) if (p) free (p)


  而在代码部分这样调用宏:

  if (expression)

  FREE1(p)

  else

  printf(“expression was false.\n”) ;


  展开后,else会和宏中的if配对了,这就错了。但是宏写成如下的形式就永远不会错了

  #define FREE4(P)  do {if(p) free(p)}; while(0)

2.如果出现在判断语句过后的宏,这样可以保证作为一个整体来是实现


  #define FOO(x) printf("arg is %s\n", x); printf("others\n");

  如果这样用:

  if (blah == 2)

  FOO(blah);

  将会被展开为:

  if (blah == 2)

  printf("arg is %s\n", blah);

  printf("others\n");;

  这样,if条件之包含了printf()语句,而 printf("others\n");调用不能按期望那样工作。而使用 do { ... } while(0)定义后,就会展开成以下语句:

  if (blah == 2)

  do {

   printf("arg is %s\n", blah);

   printf("others\n");

  } while (0);

  这是所期望的状况.

以上的情况用单独的{}也可以实现,但是为什么一定要一个do{}while(0)呢

#define FREE1(p) {if (p) free (p) }

if (expression)
FREE1(p);
else
printf(“expression was false.\n”) ;

预处理之后,就变成了这样:
if (expression)

 if(p)
 free(p)
};
else
 printf(“expression was false.\n”) ;
 

仔细看看{}后面那个分号,明白了吧?

所以只见过 do {} while(0) 这种宏,而没见过 do {} while(0); 这种宏

相关文章:

  • 2021-09-27
  • 2021-06-16
  • 2021-09-19
猜你喜欢
  • 2022-12-23
  • 2021-07-31
  • 2021-06-28
  • 2022-12-23
  • 2021-09-02
  • 2022-12-23
  • 2021-08-25
相关资源
相似解决方案