Using Haskell's 'newtype' in C

17 points by telemachus


thasso

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)

tobz619

This is a really nice trick and something I really wanted to reach for a few days ago! Thanks for this!!!

olliej

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 :-/