【问题标题】:Why is this macro used?为什么要使用这个宏?
【发布时间】:2012-01-19 06:41:16
【问题描述】:

我正在尝试使用德州仪器 (TI) 的示例编写一些微控制器代码,并且它在任何地方都使用宏(可能是为了减少代码大小),其中一些被 st() 包围。看完 cmets 后,我还是不明白为什么这是必要的,也不明白什么时候应该使用它:

/*
 *  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)

您能否举一些例子说明当 st 不存在时会发生什么失败?在不需要的地方添加 st 有什么害处吗?

st 可能代表什么? { something } 的第二个示例何时产生编译器错误?因为在一些示例代码中也使用了它。

【问题讨论】:

    标签: c macros


    【解决方案1】:

    “do {...} while (0)”是一种用于避免某些类型问题的技术。

    __LINE__ == -1 可能用于避免一些编译器警告。 __LINE__ == -1 永远是假的。

    看看这个链接,它会解释“do...while(0)”的原因

    http://cnicholson.net/2009/02/stupid-c-tricks-adventures-in-assert/

    【讨论】:

      【解决方案2】:

      例子:

      #define a(x) if(x) { printf("%s\n", "OK"); }
      int i = 1;
      if(0)
          a(i);
      else
          printf("%s\n", "KO");
      

      将扩展为相当于:

      if(0)
      {
          if(x)
          {
              printf("%s\n", "OK");
          }
          else printf("%s\n", "KO");
      }
      

      但是,如果您将a(x) 定义为:

       #define a(x) st(if(x) { printf("%s\n", "OK"); })
      

      它将起作用,扩展到:

      if(0)
      {
          do
          {
              if(x)
              {
                  printf("%s\n", "OK");
              }
          }
          while(0);
      }
      else printf("%s\n", "KO");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-25
        • 2011-08-05
        • 2013-11-09
        • 2016-04-11
        相关资源
        最近更新 更多