Re:Checked integer arithmetic in the prospect of C23
by raphlinus on Monday December 19, 2022 @04:16PM
(#34057827)
The addition operator just landed in Rust 1.66 (checked_add_signed[1]), but the subtraction one it looks like you'd need to roll your own.
Re:Checked integer arithmetic in the prospect of C23
by tialaramex on Monday December 19, 2022 @07:32PM
(#34059910)
You are probably looking at it wrong. You can now write
i32::checked_add_unsigned(some_u32) and
i32::checked_sub_unsigned(some_u32)
... which I think are exactly what your parent needs.
Re:Checked integer arithmetic in the prospect of C23
by jcranmer on Monday December 19, 2022 @09:20PM
(#34060739)
u32::checked_add_signed solves one of the pairs (u32 + i32 -> u32), but there's nothing for the other one (u32 - u32 -> i32).
Re:Checked integer arithmetic in the prospect of C23
by tialaramex on Tuesday December 20, 2022 @04:27AM
(#34063604)
Good point, I'm sure this made sense to me when I wrote it, but I can't ask past me why.
Re:Checked integer arithmetic in the prospect of C23
by TazeTSchnitzel on Monday December 19, 2022 @05:10PM
(#34058450)
> it becomes a game of try to write it in a pattern that the compiler can recognize
Worse, in C or C++ you also need to find a way to do it without undefined behaviour. You can't just do the operation and see if the result matches expectations…
Re:Checked integer arithmetic in the prospect of C23
by tinus_hn on Monday December 19, 2022 @06:54PM
(#34059586)
C is supposed to be reasonably portable so it doesn’t make too much sense to depend on flags that are not available on all platforms.
Re:Checked integer arithmetic in the prospect of C23
by int_19h on Monday December 19, 2022 @07:17PM
(#34059789)
It's easier to find a platform that doesn't support floating-point numbers than one that doesn't have some kind of overflow flag. Some kind of platform-independent abstraction is long (as in, decades) overdue.
Re:Checked integer arithmetic in the prospect of C23
by noobermin on Monday December 19, 2022 @07:19PM
(#34059811)
Sure, but it kind of is insane that there are platforms (like ARM apparently, did not know) that do NOT have a carry flag.
Although, recently, I noticed I wanted a case where I wanted checked (u32 - u32) -> i32 and (u32 + i32) -> u32 operations, which even Rust's standard library doesn't provide. (The use case is keeping track of a running delta between two lists of u32 values--the delta can go positive or negative, so it has to be signed, but the values in the lists can never be negative).