'Multipurpose' linked list implementation in pure C

前端 未结 9 1804
一生所求
一生所求 2020-12-12 16:33

This is not exactly a technical question, since I know C kind of enough to do the things I need to (I mean, in terms of not \'letting the language get in your way\'), so thi

9条回答
  •  感情败类
    2020-12-12 17:27

    This is a good problem. There are two solutions I like:

    • Dave Hanson's C Interfaces and Implementations uses a list of void * pointers, which is good enough for me.

    • For my students, I wrote an awk script to generate type-specific list functions. Compared to preprocessor macros, it requires an extra build step, but the operation of the system is much more transparent to programmers without a lot of experience. And it really helps make the case for parametric polymorphism, which they see later in their curriculum.

      Here's what one set of functions looks like:

      int      lengthEL (Explist *l);
      Exp*     nthEL    (Explist *l, unsigned n);
      Explist *mkEL     (Exp *hd, Explist *tl);
      

      The awk script is a 150-line horror; it searches C code for typedefs and generates a set of list functions for each one. It's very old; I could probably do better now :-)

    I wouldn't give a list of unions the time of day (or space on my hard drive). It's not safe, and it's not extensible, so you may as well just use void * and be done with it.

提交回复
热议问题