zoukankan      html  css  js  c++  java
  • 宏定义#define st(x) do { x } while (__LINE__ == -1) 剖析

    第一次见到#define st(x) do { x } while (__LINE__ == -1)就被困惑住了,自己之前学的C语言中从还没有过,百度后自己也总结一下。

    在Z-Stack代码,里面有这么一个定义:
     
    /*
     *  This macro(宏) is for use by other macros to form a fully valid C statement.
     *  Without this, the if/else conditionals could show unexpected behavior.
     *
     *  For example, use...
     *    #define SET_REGS()  st( ioreg1 = 0; ioreg2 = 0; )
     *  instead of ...
     *    #define SET_REGS()  { ioreg1 = 0; ioreg2 = 0; }
     *  or
     *    #define  SET_REGS()    ioreg1 = 0; ioreg2 = 0;
     *  The last macro would not behave as expected in the if/else construct.
     *  The second to last macro will cause a compiler error in certain uses
     *  of if/else construct
     *
     *  It is not necessary, or recommended, to use this macro where there is
     *  already a valid C statement.  For example, the following is redundant(多余的)...
     *    #define CALL_FUNC()   st(  func();  )
     *  This should simply be...
     *    #define CALL_FUNC()   func()
     *
     * (The while condition below evaluates false without generating a
     *  constant-controlling-loop type of warning on most compilers.)
     */
    #define st(x)      do { x } while (__LINE__ == -1)
     
    以上的英文说明解释了为什么要使用此宏定义。
     

    _LINE_是C/C++的内部宏定义,得到当前的行号。表达式(_LINE_==-1)为假。

    此宏定义使用do{  }while(  )结构避免了在引用宏定义时的错误。

    示例:

    正确形式:

    #define SET_REGS()  st( ioreg1 = 0; ioreg2 = 0; )

    不正确的格式分析:

    1、#define SET_REGS()  ioreg1 = 0; ioreg2 = 0;

    此宏定义在使用if、else格式时会报错。

    eg:

    if( 条件)

      SET_REGS()

    else

      {}

    错误原因:if-else没有接上,在SET_REGS()需加{}。

     

    2、#define  SET_REGS()   { ioreg1 = 0; ioreg2 = 0;}

    此宏定义在 

    eg:
    if(条件)
    {
      SET_REGS()
      
      其他语句;
    }
    错误原因:if中包含{}的嵌套。
     

     

     

     

     

     

     

  • 相关阅读:
    Oracle 获取本周、本月、本季、本年的第一天和最后一天(转载)
    easyui tabs页签显示在底部属性
    java mybatis XML文件中大于号小于号转义(转载)
    原生JS日历 + JS格式化时间格式
    ajax之async属性
    Easyui 行编辑
    css中实现显示和隐藏(转)
    layer弹出层 获取index
    js中关于json常用的内容、js将数字保留两位小数
    发布项目到github上web服务器来运行
  • 原文地址:https://www.cnblogs.com/liutogo/p/3576395.html
Copyright © 2011-2022 走看看