Question

I read the following question: Value of i for (i == -i && i != 0) to return true in Java and was left slightly dazzled.

One reads about spacecraft being lost because of using the wrong unit system, so seeing the behaviour mentioned in the question and awnser is quite unexpected to me.

How does one protect against the errors/unexpected behaviour generated by this, without runtime penalty? (I find it hard to think of sensefull code with the = comparison, while I consider it rather simple for abs returning a negative value to fail). Are there exceptions to catch? Linters that warn about this?


Unexpected Behaviour:

java abs() returns the minimum negative number if the input is the minimum negative number. -x=x has a solution other than 0, the minimal negative number in twos complement.

Was it helpful?

Solution

Best practice is to either

  1. Use sensible types in your system. Be aware that a machine int is not a mathematical integer. If your program may need to use numbers out of the range of a machine int, you should be using a big integer library, not machine ints.

  2. Program defensively. If an operation might result in a value going out of range, then you should explicitly check for this after the operation is performed (or, even better, check before the operation to see if the arguments will cause an error).

Of course, if you do 2. you still have to decide what to do in case an error occurs, which you don't with 1. However, using big integers will incur a performance penalty in most languages. Whether that runtime penalty is greater or less than the penalty from performing safety checks will likely depend on the programming language and the specifics of your program.

In the end, it is the programmer's job to be responsible with the code that they write. The language can only provide you with so much help.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top