Can a C macro contain temporary variables?

后端 未结 9 680
忘掉有多难
忘掉有多难 2020-12-16 15:25

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 subs

9条回答
  •  情书的邮戳
    2020-12-16 16:03

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

    1. The macro doesn't have a return statement. You can use the do while trick.

      #define macro(x) do { int y = x; func(&y); } while (0)
      
    2. 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.

提交回复
热议问题