It is definitely a must for a good programming language to support detection of integer overflows because they are a common error and the overflow detection relies on CPU flags that are available only to the compiler, but not the programmer (except in assembler ;-) ).
Basically there are the following strategies to handle something like that:
- Don't handle it. That's what C/C++ does.
This results in the corresponding data types effectively being defined as modulo their size.
- Result is largest possible value for the specific data type.
- Run-time error.
- Error indicator (e.g. errno in C).
- Special return value (NaN), like usually for floating point.
For every of these strategies, there are situations where they are appropriate and where they are not.
If we look at the strategies,
No. 1 is very error-prone and for the cases where it is really needed, it is redundant if the programming language has got a modulo operator. A good compiler should be able to detect this situation and simply disable overflow checking for this calculation, so that doesn't cost any performance, compared to the C/C++ way.
No. 2 has got the disadvantage of not being able to tell if the calculation delivered the largest result possible or an overflow occured. However, there are applications where an inaccurate result is better than a program error, so this can be useful. For these few cases, it can be emulated with any of the methods 3.-6., so it's redundant.
The strategies 3 & 4 are quite similar, so we could come along with one of them, preferably exception because it's more universal.
No. 5 belongs into the same category, but there are cases where it can simplify error handling over exceptions, etc. It's redundant with the other possibilities 3, 4 and 6
In languages that have an inline assembler, it's possible to examine the corresponding CPU flags in a non-portable way to achieve this, as long as the CPU supports this detection at all (has anyone know one that doesn't?).
No. 6 has also got huge disadvantages, it leads to the definition of the integer type being different from what's common and the special value must not be used accidentially, e.g. as the result of a successful calculation, so the compiler has to generate additional checking code for calculations. Therefore I don't like it.
In my view, the default behaviour should be an exception or something similiar to ensure that the error is noticed. The programmer should be able to disable this or switch to a "less destructive" strategy like 5 by using compiler switches or pragmas.