4 ms·
It's hard to discuss this without using any specific "type-safe" language. 1. you can have the same problem in type-safe language, since it will probably have
by mikulas_florek 10y ago
It's hard to discuss this without using any specific "type-safe" language.
1. you can have the same problem in type-safe language, since it will probably have cast to int too
2. do not use builtin operators in C for that, instead create new functions, e.g. addMeters(Meters a, Meters b);
3. hide the int in *.c file
- fiedzia 10y ago> you can have the same problem in type-safe language Yes, you can. But at least you have a better option and better chance of other people using it, so statistically you'll have less errors. > do not use builtin operators in C for that No, do not add another rule to a million of rules people have to already follow, make compiler worry about enforcing that, not developer.
- mikulas_florek 10y ago> Yes, you can. But at least you have a better option and better chance of other people using it, so statistically you'll have less errors. I highly doubt that this specific bug would not happen in any typesafe language. The only way I see this not happening is if there is no native float-like type. Is there such language? They could have make it safe in C, and they did not, probably because it's convenient to use float. > No, do not add another rule to a million of rules people have to already follow, make compiler worry about enforcing that, not developer. It can be implemented in C so it's forced by compiler.
- jasode 10y agoLook at the common theme among your suggestions: - do not use builtin operators in C for that, - instead create new functions, e.g. addMeters() - hide the int in *.c file Those are "best practices" instead of compiler-enforced type-check errors. Likewise, suggesting a best practice such as "don't free() memory twice" is not the same as a GC-language (Lisp/Java/C#/Go) freeing memory on the programmer's behalf or a static-ownership checker (Rust) preventing a programmer from making that mistake.
- mikulas_florek 10y agoYou can write the exact same wrong code in e.g. C# public class Meters { public int x; } public class Yards { public int x; } public class Kilograms { public int x; } Meters m = ... Yards y = ... Kilograms k = ... k.x = m.x + y.x; all my sugestions for C are basically the same in C# - do not use builtin operators in C# for that instead create new functions, e.g. addMeters() - hide the int in *.c file == make it private in c#
- kazinator 10y agoDon't free memory two or more times is "OMG don't flippin' do that", not a "best practice". ;) "Best practice" is a choice from among justifiable alternatives.