It's documented that "INC", "DEC" and "MUL" instructions should be used on unsigned integers but still two first instructions affect overflow and sign flags and "MUL" affects overflow flag which are flags used when dealing with signed numbers and it doesn't make sense with that documentation, So why ?
3 Answers
I'm not sure where you get the idea that inc
and dec
should be restricted to unsigned integers. Please point me at the pertinent documentation.
In general, the 8086 processor didn't have different instructions for signed/unsigned operations. The processor had built-in knowledge of how the result of an operation would be viewed in a "signed" world, but that's pretty much as far as it went. And that has been carried through to the latest iterations of the x86 processor design.
It would make little sense to have an inc
instruction that worked only with unsigned values, as then it would be either very expensive to increment a signed value (you would have to use the add
or adc
instruction to add 1), or it would be very expensive to check for overflow after doing the inc
(or dec
).
Assuming we are talking x86 here, the Wikipedia page on the overflow flag says it's set by all arithmetic operations. Which documentation are you referring to that suggests otherwise?
This is how it works:
Consider two byte values 0x65 and 0x31. They are both unsigned values regardless of whether you look at them from a signed or unsigned point of view.
Then you add them:
0x65 + 0x31 becomes 0x96 which is fine from the unsigned point of view (the sum fits in a byte so no carry flag was set). However from the signed view the addition of two positive numbers resulted in a negative number, hence the overflow and sign flags were set. In fact, for all signed numbers the overflow flag is set if the most significant bit changes as a result of the operation, otherwise it is cleared.
You can see it as if the cpu performs two operations for every instruction by setting the applicable flags for both the unsigned and the signed add. After that it is up to the compiler (or assembly programmer) to decide if an unsigned conditional branch (using flags zero and carry) or a signed conditional branch (using flags zero, sign and overflow).
So what's the point?
The point is that if it were not done in this way the processor would need one set of instructions for signed operations (that would only affect the zero, sign and overflow flags) and another for unsigned operations (affecting zero and carry).
add
operation for both, signed and unsigned values. – ruslik