Post #4335607
2026-08-02 19:32 UTC
The thing that made C finally tolerable to me for use in larger codebases is that I can now write a very high-quality type-safe dynamic array, with sane memory management. (C23 + extensions are necessary.) Some demo code is linked below.
This is only possible thanks to @thephd@pony.social driving typeof and defer to the standard. @uecker@mastodon.social and @erisceleste@tech.lgbt also pushed or are pushing things into the standard that help massively, such as if-declarations and tagless structure compatibility. Statement expressions (or closures) are the last necessity that aren't yet for sure inbound to the standard, so far as I know, but statement expressions are ubiquitous enough that I don't care.
None of this works in Microsoft's C compiler ofc, but frankly IMO there's really no reason to even try to use their toolchain anymore given that clang-cl and msys2 both exist. Something like Cake could maybe be used if MS toolchain support is critical (I haven't tried it), assuming that Cake is keeping up with C29 and onward.
This code here is all commented with examples and has some small demo code; the actual header I use in real projects is only ~200 lines with all features implemented.
https://godbolt.org/z/17rf3v3TW
I was going to write up a big description of the reasoning for this specific approach and all the crimes -- I mean techniques -- used, but I realize I haven't touched my blog in years and I need to find a new non-github host to migrate it to first.
The trickiest bit to wrangle I think was how I got the range-based loop macros to work at my target quality bar.
The solution presented here requires if-declaration support (Clang trunk), though my actual code uses some nested for-loop abuse (works in Clang 22, though labeled continue won't work correctly). The if-statements will also result in better -O0 codegen, so I'm looking forward to eventually getting my mitts on that in a deployed toolchain.
Anyway, enjoy this glimpse into the workings of my madness.
(Someday I'll write up how my strbuf_t is implemented, because it's the other workhorse that I rely on heavily to make modern C coding tolerable. It doesn't use many macros or any cutting-edge C features, though, so it's not nearly as interesting. tl;dr is that defer statements make using it sane.)
Replies (0)
No replies.