3 ms·
I wonder, is there any language that automatically promotes ints to more bits to ensure there is no overflow? The sum of two eight-bit ints is a nine-bit int (p
by captainmuon 5y ago
I wonder, is there any language that automatically promotes ints to more bits to ensure there is no overflow? The sum of two eight-bit ints is a nine-bit int (probably occupying 16 bits in memory, but that is an implementation detail):
uint8 a = 230;
uint8 b = 250;
auto c = a + b; // typeof(c) == uint9
Maybe it would even be able to detect "c / 2" fits in an uint8.
I guess this could lead to an explosion of bits required, but only if you chain multiple operations and use type inference. If you explicitly assign to a fixed-width integer, it would truncate.
I know Python used bignums under the hood, but is there any compiled and/or strictly typed language that does this? Because it seems modulo arithmethic and silent under/overflow is most of the time not what you want.
- ncmncm 5y agoThat is generally not possible in a strongly-typed language unless you just use a bignum type to begin with. Most numbers are small, and you aren't worried about overflow. With big numbers, std::int64_t is hard to overflow. If you have numbers from an untrusted source, you can and should range-check them immediately on input.
- captainmuon 5y agoWhy not? Ada, Pascal, Nim and others have ranged integer types. Many modern languages use some kind of type inference. You could easily define that the type of an integer expression has to be large enough, for most expressions. It doesn't have to be general (I wouldn't be surprized if the general case is theoretically impossible). But you could fix the most obvious cases easily with this (for loops that can't go below 0 because of unsigned counters, calculating the average but the temporary overflows, ...). And if the compiler gives you a warning... "Inferred variable would require a bignum (int128)" then you could either silence it by specifying the type explicitly, or maybe you are missing a manual range-check? > If you have numbers from an untrusted source, you can and should range-check them immediately on input. You should, but you are going to forget in some places. The point of a stongly-typed language to me is that the compiler will make sure you do. It is the edge cases and the cases where you accidentially don't sanitize properly where you get evil bugs.
- ncmncm 5y agoAnd if you do "forget in some places", Ada, Pascal, and Nim will not produce the correct response. What will they do instead? We don't need to guess, we saw in the first Ariane 5: catastrophic loss of vehicle and payload, as a result of sending a crash dump report to the engine steering gimbals. $500M payload, in that case.