Can a C macro contain temporary variables?

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

    Eldar's answer shows you most of the pitfalls of macro programming and some useful (but non standard) gcc extension.

    If you want to stick to the standard, a combination of macros (for genericity) and inline functions (for the local variables) can be useful.

    inline
    long fooAlloc(void *f, size_t size)
    {
       size_t      i1, i2;
       double   *data[7];
    
       /* do something */
       return 42;
    }
    
    
    #define ALLOC_FOO(T) fooAlloc(malloc(sizeof(T)), sizeof(T))
    

    In such a case using sizeof only evaluates the expression for the type at compile time and not for its value, so this wouldn't evaluate F twice.

    BTW, "sizes" should usually be typed with size_t and not with long or similar.

    Edit: As to Jonathan's question about inline functions, I've written up something about the inline model of C99, here.

提交回复
热议问题