Protect from missbehavior caused by two compliments

I read the following question: I value for (i == -i && i! = 0) to return true in Java and stayed a little blinded.

One reads about a spaceship is lost due to an incorrect system of units, so the vision mentioned in the question and the Einser is completely unexpected to me.

How to protect against errors / unexpected behavior caused by this without penalty for execution? (It's hard for me to think of sensefull code with matching = , although I find it pretty simple for abs return a negative value to an error). Are there any exceptions? Linters who warn about this?


Unexpected behavior:

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

+4
source share
1 answer

Best practice is either

  • Use reasonable types in your system. Keep in mind that an int machine is not a mathematical integer. If your program might need to use numbers from the machine int range, you should use a large integer library, not machine ints.

  • Defend the defense. If the operation can cause the value to fall outside the range, then you should explicitly check it after the operation is complete (or, even better, check it before the operation to see if the arguments lead to an error).

Of course, if you do 2., you still need to decide what to do if an error occurs, and you are not from 1. However, using large integers will result in poor performance in most languages. Regardless of whether this runtime is more or less than the fine from performing security checks, it will probably depend on the programming language and the features of your program.

In the end, the task of the programmer must be responsible for the code that they write. Language can only provide you with such help.

+3
source

Source: https://habr.com/ru/post/1492707/


All Articles