I am trying to mask the concept of using macros to define data structure operations. The following code is a simple example of using the built-in list library in FreeBSD. In the library, all operations are defined as macros. I have seen this approach in several other libraries.
I see that this has some advantages, for example. the ability to use any data structure as an item in a list. But I do not quite understand how this works. For instance:
- What is
stailhead? It seems "fair." - How to transfer
headand entriesin function? - What type
head, how can I declare a pointer to it?
Is there a standard name for this technique that I can use to search on Google or any book that explains this concept? Any links or a good explanation of how this technique works will be greatly appreciated.
Thanks to Niklas B. I ran gcc -Eand got this definition forhead
struct stailhead {
struct stailq_entry *stqh_first;
struct stailq_entry **stqh_last;
} head = { ((void *)0), &(head).stqh_first };
and this is for stailq_entry
struct stailq_entry {
int value;
struct { struct stailq_entry *stqe_next; } entries;
};
So, I think it headhas a type struct stailhead.
#include <stdio.h>
#include <stdlib.h>
#include <sys/queue.h>
struct stailq_entry {
int value;
STAILQ_ENTRY(stailq_entry) entries;
};
int main(void)
{
STAILQ_HEAD(stailhead, stailq_entry) head = STAILQ_HEAD_INITIALIZER(head);
struct stailq_entry *n1;
unsigned i;
STAILQ_INIT(&head);
for (i=0;i<10;i++){
n1 = malloc(sizeof(struct stailq_entry));
n1->value = i;
STAILQ_INSERT_HEAD(&head, n1, entries);
}
n1 = NULL;
while (!STAILQ_EMPTY(&head)) {
n1 = STAILQ_LAST(&head, stailq_entry, entries);
STAILQ_REMOVE(&head, n1, stailq_entry, entries);
printf ("n2: %d\n", n1->value);
free(n1);
}
return (0);
}
source
share