C Macros: How to map another macro to variadic arguments?

前端 未结 3 2048
离开以前
离开以前 2020-12-19 22:45

I\'d like to know how to apply a unary function (or another macro) to variadic arguments of a macro, like

int f(int a);

#define apply(args...) 

        
3条回答
  •  臣服心动
    2020-12-19 23:37

    Everything is possible in C if you throw enough ugly macros at it. For example, you can have an ugly function-like macro:

    #include 
    
    int f (int a)
    {
      printf("%d\n", a);
    }
    
    #define SIZEOF(arr) (sizeof(arr) / sizeof(*arr))
    
    #define apply(...)                    \
    {                                     \
      int arr[] = {__VA_ARGS__};          \
      for(size_t i=0; i

    Notice that 1) This would be much better off as a variadic function, and 2) it would be even better if you get rid of the variadic nonsense entirely and simply make a function such as

    int f (size_t n, int array[n])
    

提交回复
热议问题