Variable arguments inside a macro

后端 未结 3 1543
难免孤独
难免孤独 2021-01-27 08:17

I have two functions foo1(a,b) & foo2(a,b,c) and a macro

#define add(a,b) foo(a,b)

I need to re-define macro to accomplish,

1.if a

3条回答
  •  忘了有多久
    2021-01-27 08:57

    If you must use variadic macros, then here is a trick.

    #define add(...) _Generic ( &(int[]){__VA_ARGS__}, \
                                int(*)[2]: add2,       \
                                int(*)[3]: add3) (__VA_ARGS__)
    
    • Have the macro create a compound literal array. The size of this array will depend on the number of arguments.
    • Grab the address of the compound literal, to get an array pointer type.
    • Let _Generic check which type you got, then call the proper function based on that.

    This is 100% standard C and also type safe.


    Demo:

    #include 
    
    
    #define add(...) _Generic ( &(int[]){__VA_ARGS__}, \
                                int(*)[2]: add2,       \
                                int(*)[3]: add3) (__VA_ARGS__)
    
    int add2 (int a, int b);
    int add3 (int a, int b, int c);
    
    int main (void)
    {
      printf("%d\n", add(1, 2));
      printf("%d\n", add(1, 2, 3));
    //printf("%d\n", add(1, 2, 3, 4)); Compiler error for this.
    }
    
    
    int add2 (int a, int b)
    {
      return a + b;
    }
    
    int add3 (int a, int b, int c)
    {
      return a + b + c;
    }
    

提交回复
热议问题