How to use array of different struct type for the same job in c

Viewed 40

I have to pass array of different struct type to a function which has to perform same functionality.

void chklink_state(void *links, int count)
{
    int i;
    int ret;
    for (i = 0; i < count; i++)
    {
       if (links[i].curr_status != links[i].prev_status)
         links[i].prev_status = links[i].curr_status;
    }
 }

main()
{ 
   struct gre_info gre_infos[10];
   struct vti_info vti_infos[10];
   //populate data with some functions
   chklink_state(gre_infos, 10);
   chklink_state(vti_infos, 10);
}

But getting error compiling with gcc. If I use union I have to use switch case for different structure type. If I use casting I have to cast links to different struct type variables then have to use switch case.

Is it possible to do mentioned operation without using switch case or if else?

1 Answers

If you do not want to use unions, you could define the functionality in a macro. Macros do not have types (they are essentially just text replacement), but be careful using them because they have a number of pitfalls.

Without knowing more about the internal structure of the structs gre_info and vti_info, here is how I would define a macro to achieve your desired goal:

#define CHKLINK_STATE(LINKS, COUNT) \
    do { \
         int i; \
         int ret; \
         for (i = 0; i < COUNT; i++) \
         { \
             if (LINKS[i].curr_status != LINKS[i].prev_status) \
                 LINKS[i].prev_status = LINKS[i].curr_status; \
         } \
    } while (0)        

Notice that I wrapped the entire function definition in a do-while loop. This is to avoid one of the pitfalls I mentioned - swallowing the semicolon.

Now back in main, you would call the macro just as you would a function:

main()
    { 
       struct gre_info gre_infos[10];
       struct vti_info vti_infos[10];
       //populate data with some functions
       CHKLINK_STATE(gre_infos, 10);
       CHKLINK_STATE(vti_infos, 10);
    }
Related