见到了神奇的do{....}while(0);结构通过学习才发现其运用的精妙之处。do{....}while(0);主要是用在宏展开时防止出现错误。
一般情况我们使用#define定义一个宏比如这样:
- #include
- #define print(x) printf ("%s\njust test;\n", x);\
- printf ( "%s\nalso test;\n",x );
- main()
- {
- print ("what's this?\n");
- }
当它编译的时候会是这个样子:
- main()
- {
- printf ("%s\njust test;\n", "what's this?\n"); printf ( "%s\nalso test;\n","what's this?\n" );;
- }
这样子看着是没有错的,但是当我们如此调用print这个宏的时候编译就会出问题:
- 1 #include<stdio.h>
- 2 #define print(x) printf ("%s\njust test;\n", x);\
- 3 printf ( "%s\nalso test;\n",x );
- 4 main()
- 5 {
- 6 int i = 0;
- 7 if ( i == 0 ) <<<<<<<<<<<<<加入if....else....判断。
- 8 print ("what's this?\n");
- 9 else
- 10 printf ( "Nothing\n" );
- 11 }
出错信息是这样的:
- 7.c: In function ‘main’:
- 7.c:9:2: error: ‘else’ without a previous ‘if’
实际的编译代码是这样的:
- main()
- {
- int i = 0;
- if ( i == 0 )
- printf ("%s\njust test;\n", "what's this?\n"); printf ( "%s\nalso test;\n","what's this?\n" );; <<<<<<<<<<<<<<<<<<<问题出现在这一行
- else
- printf ( "Nothing\n" );
- }
但是如果我们用do{.....}while(0)来改变这段代码:
- 1 #include<stdio.h>
- 2 #define print(x) do{printf ("%s\njust test;\n", x);\
- 3 printf ( "%s\nalso test;\n",x );}while(0) <<<<<<<<<<<加上do{....}while(0)
- 4 main()
- 5 {
- 6 int i = 0;
- 7 if ( i == 0 )
- 8 print ("what's this?\n");
- 9 else
- 10 printf ( "Nothing\n" );
- 11 }
我们可以看到的编译的实际代码是:
- main()
- {
- int i = 0;
- if ( i == 0 )
- do{printf ("%s\njust test;\n", "what's this?\n"); printf ( "%s\nalso test;\n","what's this?\n" );}while(0);
- else
- printf ( "Nothing\n" );
- }
这样就不会有错了。并且不直接使用{}的原因是宏展开时会在后面加上一个;因此只使用{}也是会出错的。比如:
- 1 #include<stdio.h>
- 2 #define print(x) {printf ("%s\njust test;\n", x);\
- 3 printf ( "%s\nalso test;\n",x );} <<<<<<<<<<<直接使用{}
- 4 main()
- 5 {
- 6 int i = 0;
- 7 if ( i == 0 )
- 8 print ("what's this?\n");
- 9 else
- 10 printf ( "Nothing\n" );
- 11 }
宏展开后的代码是:
- main()
- {
- int i = 0;
- if ( i == 0 )
- {printf ("%s\njust test;\n", "what's this?\n"); printf ( "%s\nalso test;\n","what's this?\n" );}; <<<<<<<<出错在这
- else
- printf ( "Nothing\n" );
- }
以上就是我总结的do{...}while(0)的精妙之处。
阅读(561) | 评论(1) | 转发(0) |