5 ms·
IME the strict conversion rules in Rust and Zig can be quite a bummer for somebody coming from C because they may add a surprising amount of friction in day-to-
by flohofwoe 6y ago
IME the strict conversion rules in Rust and Zig can be quite a bummer for somebody coming from C because they may add a surprising amount of friction in day-to-day coding. Yes, C code is often way too sloppy when it comes to picking the right type (signed vs unsigned vs float), and it conveniently hides the problems if the wrong choice was made.
But sometimes the same value needs to be used in integer and floating-point math, and there is no single correct type for this value.
There are also some tricky choices in bit twiddling operations. Is it really such a problem when bits are shifted out of a value when this is normal behaviour down on the assembly level?
I guess I'll eventually learn to live with strict explicit conversion, and eventually I'll get better at picking the right type from the start, but I think implicit versus explicit conversion is an area where there is no "completely right" solution, because with 100% explicit conversions even coding down on the assembly level is more convenient ;)
- pjmlp 6y agoC programmers are well known to refer to such programming safety as straighjacket since the Pascal days anyway. There was more than enough time to learn why it was the right option to start with.
- lrfield 6y agoThe straight-jacket is the syntax in Ada. I don't feel locked in by the correctness measures, but if you are going to have elaborate declaration blocks I prefer "let foo = bar in ...". Because everything else is "let" in disguise. ML got the syntax right.
- pornel 6y agoRust does go overboard though, e.g. indexing requires `usize`. You either use `usize` for all your integers, or you end up with a cast-salad. arr[i as usize] This is actually risky, because even when you only meant to extend, you can also accidentally truncate or change sign. `as` does all of these things without a warning, and mixed with type inference it can easily lead to surprises. Rust makes it worse by insisting on a theoretical support for 16-bit and 128-bit `usize` regardless of the target platform, so you can't use `a[i.into()]` to infallibly convert `u32` to `usize` on 32-bit and 64-bit platforms. The correct syntax is: arr[usize::try_from(i).unwrap()] which is painfully verbose. In larger expressions it's almost an obfuscation of what the code is actually doing.
- pjmlp 6y agoJust wait for the updated C++ standard with size_t indexers.
- joppy 6y agoThe Rust approach of having all indexing being unsigned has been extremely annoying for programming algorithms which need to do interesting indexing patterns like walking backwards through an array while indexing into another: the fact that “i >= 0” can no longer be used as a loop condition is quite exasperating. It means other more complicated indexing or looping approaches need to be used, and when showing code to coworkers (mostly mathematicians), they puzzle over this for a while before asking “why not just use i >= 0”? It’s not just this case - doing index arithmetic in general is vastly complicated by the fact that it’s difficult to detect idx < 0. I think unsignedness on array indices is one of those places where the “make invalid states unrepresentable” mantra has gone too far: yes it’s nice that theoretically the whole 64-bit index space is addressable from a byte array based at 0, but in reality -1 is just as stupid and invalid an array index as 2^64 - 1 for pretty much every use-case. What we gain is negligible; what we lose is a lot of sensible code for dealing with index arithmetic.
- jstimpfle 6y agonegative indexing could even make sense in some situations. It's not at a far stretch to imagine a pointer pointing to the one-past-last element of a series, and use e.g. -1 to get the most recent element. Python's indexing indeed works like that way.
- bbatha 6y agoAs I'm sure you're aware, this gets lost in bike shed land every time it comes up but Rust could implement `Index<iN|uN>` pretty easily. Unlike C you don't need an implicit cast to do the right thing. Personally, I have datastructure that uses non `usize` indexes I usually wrap my vector/array in in a custom type that implements index on whatever my common index types are.
- steveklabnik 6y ago
- gavinray 6y agoYou basically have to accept the relatively small, upfront cost of verbose declarations for these sorts of things in exchange for the lack of headaches + bugs you wind up with later. Or not, you can also choose not to write these kinds of languages and nobody can blame you -- to each their own.
- p0nce 6y agoD doesn't try to "fix" C integer promotion/casts. It's because they aren't bad defaults. As a bonus you can port code from C with less risk. Soon you'll be able to compile it directly. I contributed to found the only discrepancy in D vs C code wrt integer (-byte would yield byte instead of int), and it was fixed so that they match exactly C _conventions_.
- SuchAnonMuchWow 6y agoC integer promotions are what remains of old computers systems which couldn't handle anything but a 'word'. It result in things highly inconsistent on modern 64-bit machines: For example, char/short are automatically promoted to int or unsigned int when an operation is performed on them, but this doesn't happen between int and long. Simple things like adding two int16_t together to get a int16_t in return is really hard: you need a mask and a extra explicit cast, and you rely on the compiler being smart enough to understand what you are doing and to emit just the instruction you want. But you don't need to do the same with int32_t, because reasons. This is a bad default behavior, as it doesn't match either the intuition or underlying hardware, it is inconsistent across all integer types, and to understand why it works that way you need to understand how computers works 30 years ago. D supporting C integer promotion might be a good thing for portability, but that's it.
- p0nce 6y ago> This is a bad default behavior I don't think so. A lot of existing C code relies on this, and removing the promotion will prime this code to be copy/pasted without fix. Who will rewrite all the C and C++ codecs code out there? A lot of C and C++ programmers actually ignore the int promotion rule, but their code relies on it involuntarily.
- p0nce 6y ago> adding two int16_t together to get a int16_t in return is really hard Because the first thing people will do is: int16_t a, b; a = (int16_t) ((b * 157) >> 12); and then if b * 157 doesn't promote to 32-bit it overflows in the negative and then the code is incorrect.
- themulticaster 6y agoCould you give some examples where the same value needs to be used in integer and floating-point math? I'm not quite sure if I understood you correctly, but in case you propose that integer <-> float conversion should happen implicitly I have to disagree. While implicitly converting from integer to float/double would probably be fine, implicitly converting from float/double to integer sounds like a recipe for headaches: There are just too many options (truncation/ceil/floor/rounding). Even if you decided that some option should be the standard since it makes sense in 90% of all cases (let's say rounding), you now have a difficult-to-find (since it's implicit) footgun ready to cause damage in the remaining 10% of all cases. Even in that paragraph lies a small surprise waiting to be found (at least for some people): The floating point standard IEEE 754 defines five different rounding modes - two "normal" modes (Round to nearest, ties to even as well as Round to nearest, ties away from zero) and the additional directed ones mentioned above (truncation, ceil, floor). Interestingly, the default rounding mode (Round to nearest, ties to even) is not the one you probably learnt in school (that would be Round to nearest, ties away from zero). In school, you always round up if you end up exactly between two numbers, i.e. round(0.5) = 1, round(1.5) = 2. However, this introduces a small bias that can manifest itself into a real problem, for example if you round many measurements and then calculate the mean. That's why the default floating-point rounding mode will essentially alternate between rounding up and down, i.e. round(0.5) = 0 and round(1.5) = 2. Most of the time this is not an issue and you really want the default rounding mode, but I hope this example illustrates why hiding the "implementation detail" of converting floating-point numbers to integers might not be a good idea. By the way, I just looked up the man page for round(), and to my surprise found that it will always round ties away from zero, independently of the floating-point environment. If you want to round using different rounding modes in C, you apparently have to use nearbyint() and friends after setting up the rounding mode using fesetround(). PS: Of course the rounding modes are all about rounding floating-point values, not necessarily converting them to integers, but I think the point should be clear.
- huachimingo 6y ago>Could you give some examples where the same value needs to be used in integer and floating-point math? When you want to draw a pong game in a finite matrix representation, like a screen in ncurses, you cannot have something like screen[2.1][3.5], so you have to truncate (or round, depending what you want to do) the same float coordinates to write that matrix. Of course, you could avoid these using fixed point but even there you need a type conversion.
- msaltz 6y agoI sort of felt similarly when first using Zig until it crashed with a helpful error at runtime when I was trying to cast -1 to an unsigned integer :) The debugging time that saved more than outweighed the amount of time it took to do the explicit cast.