assemblyx86-16instructionsmov

Why mov/cmp instead of cmp with two memory operands?


I came through the following statement while going through a binary search program code

l1: mov si,low_
    cmp si,high_

Why do we need to store low_ in si and then compare with high_ ? Can't we directly write cmp low_,high_


Solution

  • You cannot write cmp low_, high_.

    For such questions, always refer to the official instruction description, e.g. at https://www.felixcloutier.com/x86/cmp. Note that cmp has forms cmp r/m16, r16, for which the first operand can be either register or memory, and the second must be a register; as well as cmp r16, r/m16 which is the reverse. But there is nothing like cmp r/m16, r/m16 or cmp m16, m16. So cmp low_, high_ would be attempting to assemble an instruction which does not exist, and your assembler will reject it.

    This is the case for most x86 arithmetic instructions: one of the operands may be a memory reference, but not both. To operate on two values from memory, you must load one of them into a register first, as this code does.