llwfp

A C library for singly linked lists
Login

A C library for singly linked lists

⇦ previousnext ⇨

3. Split node and data logic using callbacks

The whole idea of linked lists with a generic data type is that it should be data agnostic.
Adding, modifying, deleting and sorting nodes in a list should be done in the same way, no matter what data type is used.
Besides, there is no need for the data handling functions to be "be aware" of that they belong to a list.

3a. Functions for data

Printing data could be done in "list-unaware" functions (no references to node_t):

    void print_int(void *data) {printf("data=%d\n", *(int *)data);}
    void print_string(void *data) {printf("data='%s'\n", *(char **)data);}
    void print_double(void *data) {printf("data=%f\n", *(double *)data);}

3b. Data-agnostic node functions

A generic function for printing node data may be implemented using a callback:

    typedef void (*print_func_t)(void *data);
    void node_print(node_t *node, print_func_t print_func)
    {
        print_func(node->data);
    }

3c. Apply the previous examples using callbacks

Printing data in main() may now be done in a more generic way (no data reference):

    node_print(node1, print_int);
    node_print(node2, print_string);
    node_print(node3, print_double);

See the example below for how to functions have been unified into node_add(), node_print(), and node_cleanup(), using callbacks.

Example 3: Using callbacks to access node data

We see that the number of functions is about the same as before (it has actually increased), but code is now less repetitive and perhaps "cleaner".
If we try hard, we may even distinguish something similar to an API interface. :-)

⇦ previousnext ⇨