Using Haskell's 'newtype' in C
17 points by telemachus
17 points by telemachus
There is a whole collection of these kinds of tricks, techniques, etc. for current day C programming. Some have been swept here over the past few days. I’m thinking it would be worthwhile writing a document to collect all these. From the comments it already seems the senior C programmers all use slightly different flavors of the same ideas that they came up with more or less organically, but what about people who are new to C? When I started using it heavily a few years ago it took me quite some time and effort to figure all of this out (fortunately I was basically HN-addicted at the time, which sped up the discovery process)
Some have been swept here over the past few days.
It me. I'm trying to learn C properly after years of higher level languages, and I'm trying to find material about C that tries to cover some of the warts and/or modernizes it. I agree with you that it would be great to have something that pulled new ideas and approaches to C together—especially since so much of what is available online about C is old or quite basic.
This is a really nice trick and something I really wanted to reach for a few days ago! Thanks for this!!!
I agree that Hungarian notation is maligned, but I feel like that’s because people do it wrong. I don’t mean (at least I don’t think I mean) in the no true Scot’s man sense - as I was introduced to it the naming was meant to indicate the type of the data not simply reproduce the type of the variable - e.g you’d have something like “sTime” to indicate “seconds”, but what seems to happen is “iTime” for “it’s an integer”, which is absolutely useless.
C++ obviously has way to make the opaque structs even more transparently act like integers, and the trivial_abi attribute also fixes (I think) the calling convention problems (in clang only I think, because it’s an extension and I don’t know if gcc has it).
But for me the thing that really kills thes struct tricks will always be bitfields :-/
You can do almost everything in c++ with an opaque enum, but there’s no way to override operator bool() on an enum class so you can’t simultaneously stop automatic lowering to an int and also have simple if (x) comparisons :-/
It’s Apps Hungarian (right but rare) vs Systems Hungarian (wrong but widespread). Sadly because the misunderstood version of Hungarian naming was used in all the Windows APIs, most people’s first exposure to it makes it seem like useless bureaucratic noise.
And then there’s the llvm coding style:
CoolTypeInterface *CTI;
Managing to get the worst of everything (facepalm emoji here)