-3

I would like to know if it is possible to code any function f that takes a structure S as a parameter while, in case we want to make drastic change to struct S, we can do it without touching a single hair of f ?

Ok, i'll share here what blows and finally your comments will help me to understand things better: They need a kind of contract, for example :

R1) each time f needs something from struct S then f access to it through a function that struct S promise to keep accessible.

  • 1
    What's wrong? It has no sensible title. It is too broad. Short answer: yes. Longer answer: it depends what the function does with/to S. – Martin Maat Feb 12 at 14:11
  • Ok, i will precise it but i am a quasi beginner. – Dadam42 Feb 12 at 14:16
  • In comment i will go on with my own vocabulary : I think the answer is yes if struct S and f have made a kind of contract. – Dadam42 Feb 12 at 14:25
4

You can do it with higher order functions (function pointers) and void pointers.

Consider this sorting code:

typedef struct node{
  void* item;
  struct node* next;
} Node;

/* Bubble sort the given linked list */
void bubbleSort(Node *start, bool greaterThan(void* a, void* b)) 
{ 
    int swapped, i; 
    Node *ptr1; 
    Node *lptr = NULL; 

    /* Checking for empty list */
    if (start == NULL) 
        return; 

    do
    { 
        swapped = 0; 
        ptr1 = start; 

        while (ptr1->next != lptr) 
        { 
            if (greaterThan(ptr1->item, ptr1->next->item))
            { 
                swap(ptr1, ptr1->next); 
                swapped = 1; 
            } 
            ptr1 = ptr1->next; 
        } 
        lptr = ptr1; 
    } 
    while (swapped); 
} 


/* function to swap data of two nodes a and b*/
void swap(Node *a, Node *b) 
{ 
    void* temp = a->item; 
    a->item = b->item; 
    b->item = temp; 
} 

By making the item in the node for the linked list a void pointer, it makes it possible to store an instance of any struct in the node.

The greaterThan function allows the bubbleSort function to work properly with any struct. For example, given the following struct:

typedef struct {
   int  book_id;
   char title[50];
   char author[50];
   char subject[100];
   char ISBN[13];
} Book;

I can compare the two books for sorting purposes:

bool bookGreaterThan(void* left, void* right)
{
  Book* a = (Book*)left;
  Book* b = (Book*)right;

  return strcmp(a->title, b->title) > 0;
}

And I can tell my bubbleSort function how to sort Books like this:

bubbleSort(firstNodeInMyBookList, bookGreaterThan);

Complete, working example here

|improve this answer|||||

Not the answer you're looking for? Browse other questions tagged or ask your own question.