Can a C macro contain temporary variables?

后端 未结 9 636
忘掉有多难
忘掉有多难 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).

    0 讨论(0)
  • 2020-12-16 16:19

    This is mostly OK, except that macros are usually enclosed with do { ... } while(0) (take a look at this question for explanations):

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

    Also, as far as your original fooAlloc function returns long you have to change your macro to store the result somehow else. Or, if you use GCC, you can try compound statement extension:

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

    Finally you should care of possible side effects of expanding macro argument. The usual pattern is defining a temporary variable for each argument inside a block and using them instead:

    #define ALLOC_FOO(f, size) \
        ({ \
            typeof(f) _f = (f);\
            typeof(size) _size = (size);\
            long      i1, i2;\
            double   *data[7];\
            /* do something */ \
            result; \
        })
    
    0 讨论(0)
  • 2020-12-16 16:21

    If you're using c++ use inline, or use -o3 with gcc it will inline all functions for you. I still don't understand why you need to macroize this function.

    0 讨论(0)
提交回复
热议问题