zoukankan      html  css  js  c++  java
  • do...while(0)的作用

    1. 消除代码的冗余以及无需使用goto语句。

    int* p = new int;
    bool bOK(true);

    do{
        bOK = func1();
        if(!bOK) break;
        bOK = func2();
        if(!bOK) break;
        //...
    }while(0);
    delete p;
    p = NULL;
     

    2. 宏定义中的do...while(0)避免悬空else分支导致编译失败或运行错误如:

    #define safe_delete(p) do{ delete p; p = NULL;}while(0)
    if (p != NULL)
      safe_delete(p);
    else
      do...sth...

    (1)如果去掉do...while(0)则会导致else无对应的if语句,导致编译错误。

    (2)假设无else语句,则宏定义中的第二句将永远执行,导致意想不到的结果

    3. 免去空语句出现编译告警。

    In older compilers, this was necessary to prevent the compiler from issuing a warning. For example:

    #define do_nothing do {} while (0)

    The current gcc compiler provides another method that can be used in place of the do-loop idiom as shown in the following example.

    #define foo ({

    statement_1;

    statement_2;

    })

  • 相关阅读:
    es6之class继承
    es6-class基本语法
    vue-cli3搭建pwa项目(一)
    vue 组件的通信方式
    react之组件&props
    React之元素渲染
    JSX
    JSX
    在项目中怎么使用react
    认识react
  • 原文地址:https://www.cnblogs.com/eric-geoffrey/p/3163783.html
Copyright © 2011-2022 走看看