C programming #define struct {} Declaration

I looked at the Glibc codes. Some glibc queue codes caught my attention. I could not give meaning to this definition of structure. This structure has no name. What for? How it works?

#define LIST_ENTRY(type) \ struct { \ struct type *le_next; /* next element */ \ struct type **le_prev; /* address of previous next element */ \ } 

A source

+5
source share
2 answers

This is actually a preprocessor macro that can be extended (most likely with a trailing name) elsewhere.

In the comments at the beginning of this header file there is a link to the queue (3) man page , which contains more detailed information about this and other macros:

The LIST_ENTRY macro declares a structure that connects items in a list.

And an example of use:

 LIST_HEAD(listhead, entry) head = LIST_HEAD_INITIALIZER(head); struct listhead *headp; /* List head. */ struct entry { ... LIST_ENTRY(entry) entries; /* List. */ ... } *n1, *n2, *n3, *np, *np_temp; LIST_INIT(&head); /* Initialize the list. */ n1 = malloc(sizeof(struct entry)); /* Insert at the head. */ LIST_INSERT_HEAD(&head, n1, entries); 

Being this C-code (and not C ++), and C has no templates, this preprocessor macro can be used to "simulate" templates (note the type parameter).

+10
source

This is a macro that is used to declare a structure type with the next and prev pointers for instances of the second structure type. This second type may be the parent type, so you can create a “linked structure” like this:

 struct foo { LIST_ENTRY(foo) list; int value; }; 

This creates a struct foo containing an element named list , which in turn is the structure in question, pointers pointing to struct foo .

Now we can create a slightly related list of struct foo like this:

 struct foo fa, fb; fa.value = 47; fa.list.le_next = &fb; fa.list.le_prev = NULL; fb.value = 11; fb.list.le_next = NULL; fb.list.le_prev = &fa.list.le_next; 

I am not 100% sure on the last line, but I think it makes sense.

+8
source

Source: https://habr.com/ru/post/1263688/


All Articles