pass block instruction as macro's argument in C

后端 未结 3 970
鱼传尺愫
鱼传尺愫 2021-01-26 18:02

I don\'t know if that is possible, I want to pass a block of instructions in macro like an argument.I will show you an example:

#define ADD_MACRO(size, BLOCK){ f         


        
3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-26 18:36

    You can do this by simply showing a block into the macro, or by using a variadic macro as suggested in another answer. However, I wouldn't recommend using macros for this purpose, as it tends to make the code less readable, more error-prone and harder to read/maintain.

    Instead, for generic programming, consider using function pointers corresponding to the desired functionality.

    Another option is to use the C11 _Generic macro to create type safe, generic code. Example:

    #include 
    #include 
    
    void int_increase (int* item)
    {
      (*item)++;
    }
    
    void char_increase (char* item)
    {
      (*item)++;
    }
    
    void int_print (int* item)
    {
      printf("%d ", *item);
    }
    
    void char_print (char* item)
    {
      printf("%c", *item);
    }
    
    void int_clear (int* item)
    {
      *item = 0;
    }
    
    void char_clear (char* item)
    {
      *item = '\0';
    }
    
    void int_traverse (int* data, size_t size, void(*action)(int*))
    {
      for(size_t i=0; i

    Output:

    2 3 4 5 6
    0 0 0 0 0
    BCDEF
    

    Simply add more of the similar kind of functions if you need to use other types.

提交回复
热议问题