Can a C macro contain temporary variables?

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

    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; \
        })
    

提交回复
热议问题