News for hackers. Stuff that matters.
Re:The C++ Iceberg by tialaramex on Wednesday May 08, 2024 @04:08AM (#40295528)
Forget gets() - that's obviously a terrible idea, and most people see immediately why, it is no longer in modern C for example.

Consider that abs() of signed integers has UB! Because the signed integers aren't balanced it's tricky to decide what should happen if we abs() the most negative value of a particular size of signed integer. In a language like Rust you get to specify what you meant here, if you don't then you get a panic when it happens. But C++ instead gives this... Undefined Behaviour!

Or take division by zero. It's easy enough to say that you think the signed integers should have wrapping arithmetic. Doesn't make much sense, but hey, it's defined at least. However, even if you define overflow as wrapping, division by zero is a different problem. In Rust they can explicitly say this can't happen using NonZero types (e.g. NonZeroI16 is a 16-bit signed integer, but it can't be zero) and get the high performance machine code, but in C++ to get that same code they just say division by zero is Undefined Behaviour.

Re:The C++ Iceberg by nneonneo on Wednesday May 08, 2024 @04:23AM (#40295605)
gets() might be (mostly) gone, but scanf(ā€œ%sā€, buf) still exists and produces no warnings or errors from the compiler.
Re:The C++ Iceberg by planede on Wednesday May 08, 2024 @05:39AM (#40296041)
How does arithmetic work with NonZeroI16 and remain efficient? What's the codegen of adding/subtracting two NonZeroI16 values?
Re:The C++ Iceberg by tialaramex on Wednesday May 08, 2024 @06:48AM (#40296476)
Whether we can efficiently do other arithmetic depends on what we're doing, but that's not necessarily on our critical path even if the division is.
Re:The C++ Iceberg by Measter on Wednesday May 08, 2024 @09:51AM (#40298125)
They don't support general arithmetic. They do have member functions for abs, multiplication, negation and power operations, but they are all checked/saturating if they can result in 0.

If you want to do actual arithmetic, you have to get the internal i16, perform the arithmetic, then rewrap it.

https://godbolt.org/z/T5e36zzM5