3 ms·
> The standard library defaults to crashing at runtime for simple float <-> integer conversion bounds errors which you’d think would be caught statically with m
by stephencanon 5y ago
> The standard library defaults to crashing at runtime for simple float <-> integer conversion bounds errors which you’d think would be caught statically with more thoughtful design.
There are very real ways in which Swift isn't ready for systems programming, but this sure ain't one of them.
- In C and C++, this doesn't trap, it's undefined behavior. Trapping is _always_ better than UB. Are C and C++ "not ready for systems-level programming"? (Yes, but that hasn't stopped people from doing it).
- C and C++ compilers don't catch this statically either by default. They just silently invoke UB (https://godbolt.org/z/seTh9cva6 https://godbolt.org/z/seTh9cva6).
- Unlike C and C++, Swift's standard library provides the tools you need to easily do something about it: if you don't want to trap, you can write `Int(exactly: x.rounded(.towardZero))` and get an Int? that is nil if a floating-point value is out of range.
There are rough edges here, but they are much, much less rough than the languages that people routinely use for systems programming. Sibling poster got at some of the real problems that _do_ need to be addressed.
- saagarjha 5y agoOne can make the argument that UB allows implementations flexibility on how they define overflow, allowing e.g. -fwrapv and trapping to be permissible based on what your desire is. But it's a fairly weak argument and doesn't detract from the rest of your points.
- stephencanon 5y agoYeah, I used to think that, but compilers are already allowed to do whatever they want in non-standard modes. Defining the result wouldn’t prevent implementing fwrapv or trapv. (Also note that neither of these applies to float-int conversions, so let’s not pretend that either helps here).