Can a C macro contain temporary variables?

后端 未结 9 681
忘掉有多难
忘掉有多难 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:19

    First, I strongly recommend inline functions. There are very few things macros can do and they can't, and they're much more likely to do what you expect.

    One pitfall of macros, which I didn't see in other answers, is shadowing of variable names.
    Suppose you defined:

    #define A(x) { int temp = x*2; printf("%d\n", temp); }
    

    And someone used it this way:

    int temp = 3;
    A(temp);
    

    After preprocessing, the code is:

    int temp = 3;
    { int temp = temp*2; printf("%d\n", temp); }
    

    This doesn't work, because the internal temp shadows the external.
    The common solution is to call the variable __temp, assuming nobody will define a variable using this name (which is a strange assumption, given that you just did it).

提交回复
热议问题