为什么使用这个宏?

end*_*ith 2 c macros

我正在尝试使用德州仪器的例子编写一些微控制器代码,并且它在任何地方使用宏(可能减少代码大小),其中一些被st()包围.阅读评论后,我仍然不明白为什么这是必要的或何时应该使用它:

/*
 *  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)
Run Code Online (Sandbox Code Playgroud)

你能举一些例子说明当st不存在时会失败吗?在没有必要的情况下添加st有什么危害吗?

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

Ren*_*ert 8

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

__LINE__ == -1可能被用来避免一些编译器警告.__LINE__ == -1永远都是假的.

看看这个链接,它将解释"do ... while(0)"的原因

http://cnicholson.net/2009/02/stupid-c-tr​​icks-adventures-in-assert/