首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么要使用这个宏?

为什么要使用这个宏?
EN

Stack Overflow用户
提问于 2012-01-19 00:29:11
回答 2查看 867关注 0票数 2

我正在尝试使用德州仪器的例子编写一些微控制器代码,它到处都使用宏(可能是为了减少代码大小),其中一些被st()包围。看完评论后,我仍然不明白为什么这是必要的,或者我应该在什么时候使用它:

代码语言:javascript
复制
/*
 *  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 }的第二个示例何时会产生编译器错误?因为在一些示例代码中也使用了这一点。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-01-19 00:35:00

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

__LINE__ == -1可能是用来避免一些编译器警告的。__LINE__ == -1将始终为false。

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

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

票数 8
EN

Stack Overflow用户

发布于 2012-01-19 00:37:18

示例:

代码语言:javascript
复制
#define a(x) if(x) { printf("%s\n", "OK"); }
int i = 1;
if(0)
    a(i);
else
    printf("%s\n", "KO");

将扩展为等同于:

代码语言:javascript
复制
if(0)
{
    if(x)
    {
        printf("%s\n", "OK");
    }
    else printf("%s\n", "KO");
}

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

代码语言:javascript
复制
 #define a(x) st(if(x) { printf("%s\n", "OK"); })

它将工作,扩展到:

代码语言:javascript
复制
if(0)
{
    do
    {
        if(x)
        {
            printf("%s\n", "OK");
        }
    }
    while(0);
}
else printf("%s\n", "KO");
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8913691

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档