zoukankan      html  css  js  c++  java
  • do..while(false)的用法总结

    首先要注意:

    do..while(0)

    代表do里面的东西至少被执行一次,在这里仅仅执行一次。

    此种用法有三个用处:
    • 代替{}代码块,实现局部作用域。在某些宏定义时非常有用:
    #define f(x) do {
         some_code;
         some_code;
    } while(0)
    (while(0)后没有分号)。
    这种语句在使用的时候比:
    #define f(x) {
         some_code;
         some_code;
    }
    (没有分号)
    不容易产生谬误。
    if(sss)
         f(x);
    esle
         ...
    此处如果不使用while(0)有可能else会跟着f(x)展开后的if走,使用while就不会产生这种情况。
    需要注意的是:
    第一种while(0)后不要加;否则在使用的时候就用成了f(x)【没有分号】,代码风格不统一。
    • 使用break跳出,带到使用goto的效果,避免使用goto【有的公司禁止使用goto】.

      

    //goto case
    
      {
    
          if(!a) gotodone;
    
          //do something here
    
          if(!b) gotodone;
    
          //do another thing here
    
          done:
    
          //final step goes here
    
      }
    
    // do ... while(0)
    
    {
    
      do
    
      {
    
          if(!a) break;
    
          //do something here
    
          if(!b) break;
    
          //do another thing here   
    
      }while(0);
    
    //final step goes here
    
    }
    • 兼容编译器
    int a;
    a = 10int b;
    b = 20
    这种代码在只支持c89的编译器上是编译不过去的,比如ADS 2.0
    int a;
    a = 10do{
    int b;
    b = 20;
    }while(0);
    这种代码在各种编译器上都能编译过去。
    • 另外,do while(0)可以保证代码在某个地方出错及时退出,而不执行后面的代码,有goto的作用,用在一些初始化或者出错不能在继续进行的代码段中。
  • 相关阅读:
    c学习第6天
    c学习第5天
    c学习第4天
    c学习第1天
    20171009/20171010/20171011
    20171010
    20171008
    20171007
    20171006
    matrix
  • 原文地址:https://www.cnblogs.com/wubugui/p/4247728.html
Copyright © 2011-2022 走看看