4 ms·
The trouble with explicit casting is if the code is refactored to change the underlying integer type, the explicit casts may silently truncate the integer, intr
by WalterBright 4y ago
The trouble with explicit casting is if the code is refactored to change the underlying integer type, the explicit casts may silently truncate the integer, introducing bugs.
D follows the C integral promotion rules, with a couple crucial modifications:
1. No implicit conversions are done that throw away information - those will require an explicit cast. For example:
int i = 1999;
char c = i; // not allowed
char d = cast(char)i; // explicit cast
2. The compiler keeps track of the range of values an expression could have, and allows narrowing conversions when they can be proven to not lose information. For example:
int i = 1999;
char c = i & 0xFF; // allowed
The idea is to safely avoid needing casts, in order to avoid the bugs that silently creep in with refactoring.
Continuing with the notion that casts should be avoided where practical is the cast expression has its own keyword. This makes casting greppable, so the code review can find them. C casts require a C parser with lookahead to find.
One other difference: D's integer types have fixed sizes. A char is 8 bits, a short is 16, an int is 32, and a long is 64. This is based on my experience that a vast amount of C programming time is spent trying to account for the implementation-defined sizes of the integer types. As a result, D code out of the box tends to be far more portable than C.
D also defines integer math as 2's complement arithmetic. All that 1's complement stuff belongs in the dustbin of history.
- simias 4y agoYeah for sure, having more expressive casts and differentiating between "upcasts" and "downcasts" is definitely better. My point that even "lossy" casts are better than C's weird arcane implicit promotion rules by quite a margin IMO. Rust's current handling of this issue is by no mean perfect, although it's been steadily improving and I definitely don't use `as` as much as I used to. >D also defines integer math as 2's complement arithmetic. I think modern C standards does so as well, but I think than signed overflow is still UB, so it's mostly about defining signed-to-unsigned conversions. There are flags on many compilers to tell them to assume wrapping arithmetic but obviously that's not standard...
- Measter 4y ago> The trouble with explicit casting is if the code is refactored to change the underlying integer type, the explicit casts may silently truncate the integer, introducing bugs. That depends on how the casting is provided. For the C-style casting, or Rust's `as` casting, yes that is a problem. However, another way casting could be provided is through conversion functions that are only infallible if information isn't lost. For example, let's say we have the functions `to_u16` and `to_i16`. For an `i8` the first function could return `Option<u16>`, the second `i16`, while for a `u8` they would return `u16` and `i16`. That way, any change to the types that could cause it to now silently truncate would instead cause a compiler error because of the type mismatch. Rust almost gets there with its `Into` and `TryInto` traits which do provide that functionality, but trying to use them in an expression causes type inference to fail, which just makes them a pain in the ass to use.
- nayuki 4y agoYou can use From and TryFrom, like u32::try_from(5i32). https://doc.rust-lang.org/std/convert/trait.From.html https://doc.rust-lang.org/std/convert/trait.From.html , https://doc.rust-lang.org/std/convert/trait.TryFrom.html https://doc.rust-lang.org/std/convert/trait.TryFrom.html
- tialaramex 4y agoAnd, notably in this context, Rust's traits are auto-implemented in a chain, so if From<Foo> for Bar, then Into<Bar> for Foo, and thus TryFrom<Foo> for Bar, and thus in turn TryInto<Bar> for Foo. This means that if first_thing used to have a non-overlapping value space so that converting it to other_thing might fail, so you wrote other_thing = first_thing.try_into().blahblahblah; ... if you later refactor and now first_thing is a subset of other_thing so that the conversion can never fail, the previous code still works fine, the try_into() call just never fails. In fact, the compiler even knows it can't fail, because its error type is now Infallible, a sum type with nothing in it, so the compiler can see this never happens, and optimise accordingly.
- WalterBright 4y agoYeah, having two different cast operations can help here. But I like the simpler approach.
- WalterBright 4y agoIt's not perfect. People do complain that: char a,b,c; a = b + c; // error a = cast(char)(b + c); // ok produces a truncation error, and requires a cast. But char types have a very small range, and overflow may be unexpected. So D makes the right choice here to promote to int, and require a cast.
- simias 4y agoArguably Rust does better for this particular example because, for debug builds and optionally release builds, overflows trigger an error. If you explicitly want wrapping arithmetic in Rust you should use b.wrapping_add(c) in this case, otherwise you'll get a runtime error. So for instance the following code generates an error (I add to add the function call indirection otherwise rustc would even refuse to compile the straightforward `200u8 + 100u8`): fn main() { println!("{}", add(200, 100)); } fn add(a: u8, b: u8) -> u8 { a + b } // thread 'main' panicked at 'attempt to add with overflow', test.rs:6:5 // note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace IMO that's a more robust and generic solution than hoping that `int` promotion will prevent the overflow. The drawback is that it incurs a performance hit and is therefore only enabled in debug builds by default.
- iFreilicht 4y agoI actually dislike this solution, because it relies on tests, while this could easily be a compile-time error. Not sure I like that D promotes implicitly and then complains about the result of the addition not being assignable to a `char`. But in theory, every integer could just have the maximum range of values encoded in its type, and for every arithmetic operation the compiler could check if the maximum range of the integer type is exceeded. You could set the range explicitly: fn mult_col(color:u8<0..31>, factor:u8<0..8>): u8<0..248> { color*factor } Or make the function generic over any range of inputs where the possible range of outputs provably fits the output type, which would be the default. There are crates that add ranged integers as types, but I haven’t found them satisfactory to work with.
- WalterBright 4y ago
- loeg 4y agoThe most recent C standards also explicitly define integer math as 2’s complement. Admittedly, much later than D.
- WalterBright 4y agoThe last 1's complement machine I encountered was, never. Not in nearly 50 years of programming. I think those machines left for the gray havens before I was born. C should also make char unsigned (D does). Optionally signed chars are an abomination.
- xeeeeeeeeeeenu 4y ago>The last 1's complement machine I encountered was, never. Not in nearly 50 years of programming. I think those machines left for the gray havens before I was born. Unisys OS 2200 uses one's complement[1] and Unisys MCP uses signed magnitude[2]. Both are still around. [1] - https://public.support.unisys.com/2200/docs/CP19.0/78310422-013.pdf https://public.support.unisys.com/2200/docs/CP19.0/78310422-... (page 108) - "UCS C represents an integer in 36-bit ones complement form (or 72-bit ones complement form, if the long long type attribute is specified)." [2] - https://public.support.unisys.com/aseries/docs/ClearPath-MCP-20.0/86002268-209/86002268-209.pdf https://public.support.unisys.com/aseries/docs/ClearPath-MCP... (page 304) - "ClearPath MCP C uses a signed-magnitude representation for integers instead of two’s-complement representation. Furthermore, ClearPath MCP C integers use only 40 of the 48 bits in the word: a separate sign bit and the low order 39 bits for the absolute value."
- mypalmike 4y agoIMO everyone gets it wrong. In a CPU instruction set, signed and unsigned are operations, not values, so why not extend that to low level languages? An int32 is neither signed nor unsigned. When you compare them, you choose signed or unsigned comparison. Rust gets points in my book for being more explicit and avoiding arbitrary promotion rules. Plus the standard lib has specific functions for things like add with overflow which reflect what the CPU flags are doing.
- 4y ago
- scrame 4y agoI never really clicked with D, but I always like reading your discussions on these details.
- WalterBright 4y agoD doesn't have any one big feature. It's an accumulation of little things, like a nice desk vs one made out of plywood. :-) People who've used it for a while discover that they're more productive and their code has fewer bugs. Sort of like putting a nut on a grade 8 bolt rather than a hardware store bolt. People don't always agree on what's better: https://digitalmars.com/d/archives/digitalmars/D/Movement_against_float.init_being_nan_363359.html https://digitalmars.com/d/archives/digitalmars/D/Movement_ag... and sometimes the rationale for things isn't obvious at all, and even counter-intuitive.
- afiori 4y agoIn the examples from the quiz the most tricky promotions IMO are that unsigned shorts are promoted to signed int instead of unsigned int, as signed and unsigned have very different behaviors.
- WalterBright 4y agoBack before the 1989 C Standard, there was a huge debate about whether to do "value preserving" versus "sign preserving" integer promotions. About half the C compilers did the former, half the latter. Compromise wasn't possible. Value preserving won. And hence unsigned shorts are promoted to signed ints.