do while(0)的妙用

来源:互联网 发布:小众软件官网 编辑:程序博客网 时间:2024/06/07 12:23
        当我刚看见do while(0)语句的时候,相信大家和我的感觉一样,这还不是相当于没有循环么,么啥作用,底下就是和大家分享这种技巧的妙用.
        do while(0)这种技巧的使用,一般都会出现在函数宏当中,使用它可以解决烦人的分号问题.估计第一次接触到这个的人现在已经充满了疑问.咱分析底下源代码.


点击(此处)折叠或打开

  1. #include<stdio.h>
  2. #include<math.h>
  3. #include<stdlib.h>
  4. #define SQUARE(num) num=sqrt(num);printf("%f\n",num); //Function Macros
  5. int main(void)
  6. {
  7.     float n;
  8.     scanf("%f",&n);
  9.     if(n>0)
  10.         SQUARE(n);
  11.     else{
  12.         printf("the number is negative number!\n");
  13.         exit(1);
  14.     }
  15.     return 0;
  16. }
注意看这个Function Macros(函数宏)的定义



点击(此处)折叠或打开

#define SQUARE(num) num=sqrt(num);printf("%f\n",num);//Function Macros




当你运行这个程序时,这块提醒一点,这块要加入链接函式库才可以正常编译,即 gcc test.c -lm
这块大家有问题的话,自己想办法解决.当编译完之后,大家会发现出现以下错误.

点击(此处)折叠或打开

  1. test.c: In function ‘main’:
  2. test.c:10: error: ‘else’ without a previous ‘if’
什么原因呢,接下来给大家分析分析.
       大家看这函数宏,当main()函数执行到SQUARE(n)时候,简单的函数宏替换之后,如下

点击(此处)折叠或打开

  1. if (n>0)
  2.    n=sqrt(n);
  3.    printf("%f\n",n);
  4. else{
  1.         printf("the number is negative number!\n");
  2.         exit(1);
  3.     }
        相信大家这下就理解造成这个错误的原因了吧.因为if语句底下由两条语句,而如果不用花括号的话,底下的else语句就没有与其匹配的if语句.估计这个时候大家就想,那我在定义函数宏的时候加上花括号行不,如下

点击(此处)折叠或打开

  1. #define SQUARE(num) {num=sqrt(num);printf("%f\n",num);}
  2.                                       //Function Macros
        这样当然可以,但是在编写程序的时候有一个习惯,那就是在每一条语句后面加上 ; 号,所以这种方式在调用的时候替换后如下:

点击(此处)折叠或打开

  1. if (n>0){
  2.     n=sqrt(n);
  3.     printf("%f\n",n);
  4.    };
  5. else{
  6.         printf("the number is negative number!\n");
  7.         exit(1);
  8.     }
    这样的话在编译if语句的时候就会出错.

   下来就是do while(0)语句的妙用
    我们把函数宏修改成为底下的形式
   

点击(此处)折叠或打开

  1. #define SQUARE(num) do{num=sqrt(num);printf("%f\n",num);}while(0) //Function Macros
就会避免上面的所有错误,函数宏替换后如下


点击(此处)折叠或打开

  1. if (n>0)do{
  2.     n=sqrt(n);
  3.     printf("%f\n",n);
  4.    }while(0);
  5. else{
  6.         printf("the number is negative number!\n");
  7.         exit(1);
  8.     }
相信通过这几个例子的分析,大家对do while(0)技巧有所掌握



















<script>window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"0","bdSize":"16"},"share":{}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];</script>
阅读(93) | 评论(0) | 转发(0) |
0

上一篇:我的25年嵌入式生涯-周立功

下一篇:do while(0)的妙用

相关热门文章
  • A sample .exrc file for vi e...
  • IBM System p5 服务器 HACMP ...
  • 游标的特征
  • busybox的httpd使用CGI脚本(Bu...
  • Solaris PowerTOP 1.0 发布
给主人留下些什么吧!~~
原创粉丝点击