Aren't the cases where you actually want an over/underflow the exception? Why not resort to special instructions/macros/operators for these operations?
Aren't the cases where you actually want an over/underflow the exception? Why not resort to special instructions/macros/operators for these operations?
int32 a, b = ...;
a+b; // there is a check
// implicitly:
// if (MAX_INT32 - a <= b) throw OverflowException;
// a+b;
but int32 a = ...;
// after here: typeof(a) = int32
int32 b = rand_int(0, 1000);
// after here: typeof(b) = int32[x|where x >=0 and x < 1000]
if (a < 500) {
// in here: typeof(a) = int32[x|where x < 500]
a+b; // the overflow check can be elided
}
So the compiler would be able to narrow down the type of a variable, and know what operations are safe to perform. This is probably impossible in the general case (halting problem and so on), but I believe it is very doable if you restrict yourselves to a limited number of subranges. This is like a kind of dependent types, but completely internal (you could expose them, if you wanted though).The compiler can't only use this extra information to remove overflow checks, but you can also have a language that guarantees there is no overflow - add two int32 and the result is an int64, and so on. And if it can infer that the result fits in an int16, then it can put it in there. But most of the time you would just use int, which means: integer variable of enough length to store my data. int8, int16, int32, maybe a BigNum. Kind of like python does it, but with the ability to pick optimized native types if needed.
https://github.com/rust-lang/rfcs/blob/master/text/0560-inte...
It's only hard to test the flags in "standard" C (I don't know if it's better with newer standards or those in progress) but the CPUs do their work on the hardware level.
It's the languages that should be changed to be able to simply check the overflow after the critical operations, not the CPUs. The overflow checks are needed only where something can "go wrong" not everywhere.
I know modern ARM instruction sets don't have conditional instructions like that, but they may have something similar for extremely infrequently triggered control flow. The same kind of trick can be handy in a variety of programming language and GC implementation techniques.
This is defined and perfectly normal.
However signed integers will cause undefined behavior on overflow and there is a common flag in most compilers to trap on overflow.