Hacker News new | ask | show | jobs
by SAI_Peregrinus 589 days ago
C has a rather weak type system: using one enum type in a function that takes a different enum isn't guaranteed to be an error, instead they promote to an integer type and silently convert (though you can set up most compilers to make this an error, e.g. `-Wenum-conversion` and `-Werror` for GCC & Clang).

The basic idea is the "newtype" pattern: different types may have exactly the same valid set of values, but not be interchangeable.

E.g. kilograms and US customary pounds, or meters and miles. If you've got a function `f(distance: double)` where `distance` needs to be in kilometers but your program also handles miles, it's nice to be able to define a type for kilometers that's different from the type for miles so the function won't compile if passed in miles incorrectly. So you get `f(distance: kilometers)`. That also stops someone passing in pounds to `f`, or any other such nonsense.