#define st(x) do { x } while (__LINE__ == -1)

来源:互联网 发布:db2 sql 正则表达式 编辑:程序博客网 时间:2024/05/29 08:42
#define st(x)      do { x } while (__LINE__ == -1)1, __LINE__ 是个宏,它代表当前代码在源文件的行号,它是大于0的,所以__LINE__ == -1 等同于0,化简为:#define st(x)      do { x } while (0)2,do {} while (0)通常用于宏中, 为的是避免如下情况:#define st(x) x那么我们在调用 if (0) st(a = b; b = c;) 时会被解释成if(0)    a = b;b = c;可见 if 只对a = b;起作用。
在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__ 是个宏,它代表当前代码在源文件的行号,它是大于0的,所以__LINE__ == -1 等同于0,化简为:
#define st(x)      do { x } while (0)

Example:

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

Will expand to something equivalent to:

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

However if you define a(x) as:

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

it will work, expanding to:

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

0 0