3 ms·
I understand the C bit to be mostly an aside, and I wouldn't really say anything there is incorrect, but I think it's worth noting here: In C, `typedef` only "
by dllthomas 11y ago
I understand the C bit to be mostly an aside, and I wouldn't really say anything there is incorrect, but I think it's worth noting here:
In C, `typedef` only "defines a type" as far as the parser is concerned. Beyond that it is treated exactly the same as if you'd spelled it out. A `typedef` can be useful for brevity, for documentation, and to DRY up usage of the type, but it does not get you nominal typing!
That said, you can get nominal typing (for a fairly low, but present, syntactic cost) by wrapping primitives in a single-element struct. This keeps the types distinct through the type checker, but is typically stripped away long before code generation so there shouldn't be any run-time cost for the additional safety.
As I've practiced, it looks like this:
typedef struct price { int64_t v; } price;
typedef struct bid { price v; } bid;
typedef struct ask { price v; } ask;
price price_difference(price p1, price p2) {
price r = { p1.v - p2.v }
return r;
}
price compute_spread(bid b, ask a) {
return price_difference(a.v, b.v);
}
Examples, of course, overly simplified for the sake of being examples. If all the .v's are getting messy, I don't feel too bad about unwrapping locally - but passing primitives between functions has become a bit of a smell.