Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic list manipulation function in C?

What is a generic list manipulation function in C? (I saw this when I was going through some materials.)

What is the difference between this function and a function which can accept elements of any kind?

Are they same...? How can we implement them individually if they are not same?

like image 719
Manoj Doubts Avatar asked Nov 28 '08 16:11

Manoj Doubts


People also ask

How to create generic list in C?

Unlike C++ and Java, C doesn't support generics. How to create a linked list in C that can be used for any data type? In C, we can use a void pointer and a function pointer to implement the same functionality.

What are generic functions in C?

A generic function is a function that is declared with type parameters. When called, actual types are used instead of the type parameters.

What is generic type in C?

Generics are syntax components of a programming language that can be reused for different types of objects. Typically, generics take the form classes or functions, which take type(s) as a parameter. Generics are also commonly referred to as templates , and in C++ are officially called templates.

Does C have a list function?

C and its standard library don't offer any list specific functions.


1 Answers

C has no concept of "generic" pointers or objects - the closest you can get is using a void* pointer. If you want one piece of code to be able to handle any data type, you pretty much have to use void* pointers. For data types with sizes no larger than a pointer, you can cast between the type and void*; for larger data types, you'll have to use dynamic memory and have the void* member point to the dynamic memory. Just watch out for memory leaks!

typedef struct list_node {
  struct list_node *next;
  void *data;
} list_node;

void list_insert(list_node *node, void *data) {
  // ...
}

On the other hand, if you want to generate code for each possible data type, you'll have to do it with macros, and then instantiate the macros for each data type you might use. For example:

#define DEFINE_LIST(type) \
  typedef struct list_node_##type { \
    struct list_node_##type *next; \
    type data; \
  }

#define IMPLEMENT_LIST_INSERT(type) \
  void list_##type##_insert(list_node_##type *node, type data) { \
    ... \
  }

DEFINE_LIST(int);     // defines struct list_node_int
DEFINE_LIST(double);  // defines struct list_node_double
IMPLEMENT_LIST_INSERT(int);    // defines list_int_insert
IMPLEMENT_LIST_INSERT(double); // defines list_double_insert
like image 116
Adam Rosenfield Avatar answered Sep 23 '22 09:09

Adam Rosenfield