Search code examples
performanceswiftlanguage-agnosticarithmetic-expressions

Is Swift the only (mainstream) language with overflow checking arithmetic?


I started studying Swift language today. I've leaned up to basic and advanced operators.

To me, the fact that all the default arithmetic operations in Swift are checked against overflow/underflow is a little surprising.

Is there any other mainstream language with this feature?

Is Swift runtime's arithmetic could be sub-optimal (performance wise) because of this?

Why did they include this feature in the language, and if it's good, why others don't already use it?


Solution

  • Performance

    There's necessarily a cost to that kind of verification. At the lowest level, the operation which causes the overflow takes a single CPU operation. Checking that there was or not and overflow during this operation requires at least one more operation (e.g. using jump operations (branching) which consider the overflow flag).

    Note that, depending on the actual code, there are probably a good number of optimizations which can be done during compilation to avoid making the time consuming check on every operation (simple example: 32-bit 0 + any short cannot overflow).

    So, yes, it's sub-optimal to include the check.

    Why

    Some languages include this kind of check to remove the burden from the programmer. If the programmer doesn't have to check himself, he can't make the mistake of not checking. If programmers in a given language can't make a certain class of mistakes, the language's reputation goes up a little bit regarding it's reliability.

    As to why some other languages don't include the checks... Different language designers have different philosophies. For some it's important to allow programmers to create programs which are as fast as they theoretically can be. For some others, it's more important to help programmers code correct and robust programs. For example, C/C++ have the reputation of rendering super fast programs, while Ada has the reputation of not even compiling until your program is most probably correct.

    Sometimes it's a matter of philosophy, sometimes it's a matter of needs. On small micro-controllers (little memory, slow clock), you don't want to have too many automatic checks because it may significantly slow down the program's execution.

    Other languages

    Here's a small table about the different ways languages deal (or not) with integer overflow. Some languages leave it to the programmer. Some raise an exception. Some will change the data type to accept the result without error (e.g.: int to long, long to BigInteger).