22

Can some one provide minimal example of TAILQ usage out of linux system library with explanation in c which can be compiled using gcc in Linux?

jxh
  • 69,070
  • 8
  • 110
  • 193
Khamidulla
  • 2,927
  • 6
  • 35
  • 59

1 Answers1

42

The TAILQ_ENTRY macro is used to establish the pointers used to insert items into the list. You place it into your structure that you want to list up.

struct foo {
    TAILQ_ENTRY(foo) tailq;
    int datum;
    /* ... */
};

The TAILQ_HEAD is used to define a structure that will act as the container for your link list elements. You provide it with a structure name, and the name of the type that it will contain.

TAILQ_HEAD(fooq, foo);

Use TAILQ_INIT to initialize an instance of your list container.

struct fooq q;
TAILQ_INIT(&q);

Use the TAILQ_INSERT_* macros to add elements.

struct foo data[3] = { foo(3), foo(7), foo(1) };
TAILQ_INSERT_HEAD(&q, &data[0], tailq);
TAILQ_INSERT_AFTER(&q, &data[0], &data[1], tailq);
TAILQ_INSERT_TAIL(&q, &data[2], tailq);

You can use TAILQ_FOREACH and TAILQ_FOREACH_REVERSE to traverse the list.

struct foo *p;
TAILQ_FOREACH(p, &q, tailq) {
    printf(" %d", p->datum);
}
puts("");

If you want to iterate over the list while removing all its elements, it is probably easier to use a while loop and use the TAILQ_EMPTY and TAILQ_FIRST macros.

while (!TAILQ_EMPTY(&q)) {
    p = TAILQ_FIRST(&q);
    TAILQ_REMOVE(&q, p, tailq);
    /* ... */
}

The above code was mostly taken verbatim from an example I wrote and tested on IDEONE.

jxh
  • 69,070
  • 8
  • 110
  • 193
  • 4
    [Try it online!](https://tio.run/##rVJda4MwFH3Pr7hzrMRhN7s@7MGtIFtKhbXdUimMUYqoXQVr/YhbR/G3u0QtjaXsaRGjuTn3nMu51@1@um5ZXgaRG@aeDw8Z84LtzXqApNBPdpvkfu6LMMpYmrsMVtst7BHwZZvWy9uSTGz6jnlUBeYEYWJUd0HEwHNYvjFQYbRyxYvF9ZcTqg2TdL2DR9jzR9dAh0ITKChqztRneRrBjlMiVIuPiPkstBNNJKtcSTBvnCACrKJT8gSa6iQ9XqTz0V9UqvyM@2pFhe@bb089yEtJ1zFXOlpgTSwbdxLVaMVmhNp1gR1eXqcS0hda7dI5rDm0CT0B13@9v9LEQcq6k7ASeDilxHwa4ZjjkgOisV@sOOXOrbACV56iQdwdVN1r9Ipqj3OWYUU5y7ukZE7ojBz46578g8r3Ogh9wBfNsI1f7XdhdYuUN68pxqIzqRPHKikZT@ekciluW1kgebZ0Pltl@Qs "C (gcc) – Try It Online") – jxh Nov 07 '18 at 21:02