内核里的do{}while(0)
2007-07-26 09:16
141 查看
为啥内核里有这么多 do{ }while(0) 的宏啊?一开始我也好不明白。感觉不出用了会有什么效果。不过明白之后就知道它的好处了。好处就在于多语句的宏。
在代码中使用:
预编译展开后:
看到了吧,do_something函数已经脱离了if语句的控制了。这可不是我们想要的。使用do{}while(0);就万无一失了。
展开后:
看到了吧,else成了语法错误了。使用do{}while(0)就不会有这个问题了。
嗯,现在明白之后,自己的代码也记得用啊!
[/code]
#define FOO(x) print(”arg is %sn”,x);do_something(x);
在代码中使用:
if(2==blah) FOO(blah);
预编译展开后:
if(2==blah) print(”arg is %sn”,blah); do_something(blah);
看到了吧,do_something函数已经脱离了if语句的控制了。这可不是我们想要的。使用do{}while(0);就万无一失了。
if (2== blah) do { printf(”arg is %sn”, blah); do_something(blah); } while (0); 当然你也可以使用下面这种形式: #define exch(x,y) { int tmp; tmp=x; x=y; y=tmp; } 但是它在if-else语句中会出现问题。如: [code]if (x > y) exch(x,y); // Branch 1 else do_something(); // Branch 2
展开后:
if (x > y) { // Single-branch if-statement!!! int tmp; // The one and only branch consists tmp = x; // of the block. x = y; y = tmp;v}; // empty statementelse // ERROR!!! “parse error before else”do_something();
看到了吧,else成了语法错误了。使用do{}while(0)就不会有这个问题了。
if (x > y) do { int tmp; tmp = x; x = y; y = tmp; } while(0); else do_something();
嗯,现在明白之后,自己的代码也记得用啊!
[/code]
相关文章推荐
- 内核代码宏中 do{...}while(0) 的作用
- 内核代码宏中 do{...}while(0) 的作用以及宏中#和##的作用及典型应用
- do{...}while(0)what is it good for?
- 黑马程序员——选择结构if、switch,循环结构while、do-while、for
- php内核分析(四)-do_cli
- do/while(0)的妙用
- 解决代码逻辑嵌套过多的技巧 do{} while(0);
- Linux中的do{...} while(0)
- do{...}while(0)的意义
- 【swift】15-0521 控制流---for,while,do-while
- 第3章 基本概念(5)语句:if语句 do-while语句 while语句 for语句 for-in语句......
- EGOImageLoading在UITableView滚动时无法加载图片do not load while scrolling
- do...while(0)的妙用 (转)
- Java 循环语句之 while ,do ...while,for
- javascript 循环语句 while、do-while、for-in、for用法区别
- do...while(0)的妙用
- do...while(0)神奇
- do{}while(false)
- #define fun() do {a***; b***;} while(0)在if语句后的用法探讨
- do {...} while (0) 在宏定义中的作用