how can I avoid the use of #if in a polymorphic print macro

后端 未结 4 675
终归单人心
终归单人心 2021-01-26 11:41

Let\'s try to run the following code:

#include 
#define MY_MACRO1(isArray,y) do { \\
                      if(isArray) \\
                                 


        
4条回答
  •  悲&欢浪女
    2021-01-26 12:23

    Is there anyway to call a #if statement inside a macro?

    Not possible.

    if not, how can I do such a thing?

    You could use C11 _Generic:

    #include 
    
    void int_func (int obj)
    {
      printf("%d\n", obj);
    }
    
    void int_arr_func (const int* obj)
    {
      printf("%d\n", obj[0]);
    }
    
    void float_func (float obj)
    {
      printf("%f\n", obj);
    }
    
    #define MY_MACRO2(y) _Generic((y), \
      int:   int_func,                 \
      int*:  int_arr_func,             \
      float: float_func ) (y)
    
    
    int main (void)
    {
        int a = 38;
        int b[]={42};
        float pi = 3.14f;
    
        MY_MACRO2(a);
        MY_MACRO2(b);
        MY_MACRO2(pi);
        return 0;
    }
    

提交回复
热议问题