Type Safe Generic Data Structures in C

(danielchasehooper.com)

64 points | by AlexeyBrin 2 days ago

6 comments

  • lor_louis 1 hour ago
    I wrote a summarizing article on type safe container types a while back, but with some C23 specific changes and a few tweaks to work better for complex types.

    https://louissven.xyz/article/how_I_do_container_types_in_C....

    Feel free to flag/delete if this isn't the place.

  • veexx103 49 minutes ago
    Is it feasible to create a new language by adding features to C

    just as was done with C++?

    • nikbackm 15 minutes ago
      There are already plenty of such languages, Zig among others.
    • pjmlp 16 minutes ago
      And Objective-C, yet somehow people reinvent them badly in C.
  • tniemi 50 minutes ago
    That `(1 ? (item) : (list)->payload)` was a neat trick. It gets optimized away, but the type comparison happens before that.

    Still feels a bit like a party trick, but if it works...

    • Xirdus 33 minutes ago
      Expressions that compile but never evaluate are bread and butter in C++ template metaprogramming.
  • rramadass 1 hour ago
    Also see Templates in C by David Priver - https://www.davidpriver.com/ctemplates.html

    He also has other interesting C techniques, namely;

    Adding reflection to C - https://news.ycombinator.com/item?id=49964525

    _Generic for Type Reification in C - https://www.davidpriver.com/creification.html

    See also his C2y interpreter with REPL named "DrC" for the upcoming C29 standard (https://en.wikipedia.org/wiki/C29_(C_standard_revision)) - https://github.com/drpriver/drc

    PS: I really like his style of writing and presentation; concise and precise without unnecessary fluff and page beautifying.

    • podocarp 1 hour ago
      Lol at some point just implement a small compiler in C… reflection is kinda a hilarious thing to have like I understand the use case for generics, since it's not that that that hard to do with macros and quite commonly wished for
  • nice_byte 9 minutes ago
    I've tried doing this for a few years and it just sucks ass. Just use c++ and templates if you need proper generic data structures. C is a defective language.
  • carlos256 25 minutes ago
    Jesus, I hate those macro hacks so much. Most of the time you only need a single container, so writing an ad-hoc implementation is cleaner than that.
    • pjmlp 15 minutes ago
      The extent some will go to avoid touching C++.