What is the difference between subtracting `x` and adding` -x` to an x86 machine?

Are there any differences in semantics? Is it possible that any of them will be faster in certain circumstances?

+7
source share
3 answers

If you have -x precomputed, then sub smth, x and add smth, -x will execute equally fast.

Semantically, there will be a difference in terms of the state of the flags.

Consider doing 8-bit addition and subtraction:

 0x01 - 0x01 = 0x00, CF = 0 0x01 + 0xFF = 0x00, CF = 1 
+13
source

In addition to different flags, if x is a constant, choosing one or the other can lead to shorter coding (rarely).

Add and subtract, both have the form op r/m32, imm8 , where the immediate operand is a byte, but this byte is extended. Thus, add edx, 128 will need to be encoded with dword immediately, but sub edx, -128 can be encoded with a character extension (saving 3 bytes).

+5
source

As noted by Alexey Frunze, there is a difference in the state of the flag. In addition, there is a difference in the number of possible displayed values. In a two-component number system, there is one more negative value than positive ones. Adding a negative number will allow you to take advantage of this, subtracting a positive number will not.

EDIT:

The main problem is that what we usually consider to be “whole” is not really whole. In mathematical terms, they are members of the ring of factors , a concept from abstract algebra. This means that for every 32-bit integer a there is another 32-bit integer b such that a + b = 0 . Whether these numbers are “positive” or “negative” is simply an interpretation. This means that my point is true and false. In terms of the factor ring, this is not true, but from the point of view of our usual interpretation, this is correct. There must be some number that we can subtract and get the same result as if we added -2147483248. This number is not 2147483248, however, which seems to contradict intuition.

+3
source

All Articles