paul
paul

Reputation: 27

Same function for different values of members in a structure

I am trying to use the same function for different values of members of a structure in C. Actually, my function is large and I do not want to re-write it again and again. So, is there any other way to achieve that?

typedef struct {
     int xpos;
     char label[30];
     fielddesc field;
} editordesc;

I want to change the xpos and some others members using the same function:

void edit(void)
{
   editordesc setf[] = { 5,"Description", 40, 0, plu.rec.DESCRIPTION };
   // code
}

void edit1(void)
{
   editordesc setf[] = { 10,"Date", 50, 10, plu.rec.Date };
   // code
}

Edit: I want to use edit() multiple times into my main() and the only thing that I want to change each time is only some values inside setf[]. So is there any alternative way? I do not want to re-write the same function again and again with different names and just only changing the values of setf[]

Upvotes: 0

Views: 227

Answers (1)

kiran Biradar
kiran Biradar

Reputation: 12742

There are multiple ways.

  1. Take structure as parameter to the function.

    void edit(editordesc var);
    

    And call the function two times.

  2. Or have array of structure and loop over it.

    void edit(void)
    {
       editordesc setf[] = {{ 5,"Description", 40, 0, plu.rec.DESCRIPTION },
                        { 10,"Date", 50, 10, plu.rec.Date }};    
    
        for (unsigned int i = 0; i < sizeof(setf)/sizeof(setf[0]); i++) {
             //printf("%d",setf[i].xpos);
             //your code
        }
    }
    

Upvotes: 2

Related Questions