一个C宏可以包含临时变量? [英] Can a C macro contain temporary variables?

查看:513
本文介绍了一个C宏可以包含临时变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我需要macro'ize功能。该函数包含临时变量,我不记得是否有关于宏替换使用临时变量的任何规则。

I have a function that I need to macro'ize. The function contains temp variables and I can't remember if there are any rules about use of temporary variables in macro substitutions.

long fooAlloc(struct foo *f, long size)
{
   long      i1, i2;
   double   *data[7];

   /* do something */
   return 42;
}

MACRO形式:

MACRO Form:

#define ALLOC_FOO(f, size) \
{\
   long      i1, i2;\
   double   *data[7];\
\
   /* do something */ \
}

这是好吗? (即没有讨厌的副作用 - 比通常之外的其他:没有类型安全等)。顺便说一句,我知道。宏是邪恶 - 我只是必须使用它在这种情况下 - 没有太多的选择。

Is this ok? (i.e. no nasty side effect - other than the usual ones : not "type safe" etc). BTW, I know "macros are evil" - I simply have to use it in this case - not much choice.

推荐答案

有只有两种情况下,它可以在任何合理的方式。

There are only two conditions under which it works in any "reasonable" way.


  1. 宏没有return语句。您可以使用做的,而伎俩。

#define macro(x) do { int y = x; func(&y); } while (0)


  • 您只针对GCC。

  • You only target GCC.

    #define min(x,y) ({ int _x = (x), _y = (y); _x < _y ? _x : _y; })
    


  • 这将有助于如果你解释为什么的,你必须使用一个宏(是否你的办公室有宏观星期一什么?)。否则,我们无法真正的帮助。

    It would help if you explain why you have to use a macro (does your office have "macro mondays" or something?). Otherwise we can't really help.

    这篇关于一个C宏可以包含临时变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆