The XCHG instruction

Exchange the contents of a register or a memory location with the contents of a register.

The XCHG instruction format

InstructionDescription
XCHG AX, reg16Exchange the contents of reg16 with AX.
XCHG reg16, AXExchange the contents of AX with reg16.
XCHG reg/mem8, reg8Exchange the contents of reg8 with reg/mem8.
XCHG reg8, reg/mem8Exchange the contents of reg/mem8 with reg8.
XCHG reg/mem16, reg16Exchange the contents of reg16 with reg/mem16.
XCHG reg16, reg/mem16Exchange the contents of reg/mem16 with reg16.

Exchanges the contents of the destination (first) and source (second) operands. The operands can be two general-purpose registers, or a register and a memory location. When a memory operand is referenced, the locking protocol of the processor is automatically implemented for the duration of the exchange operation, regardless of the presence or absence of the lock prefix or the IOPL value.

This instruction is useful for implementing semaphores or similar data structures for process synchronization.

Usage example

title Author: Evgeny Sergeevich Dovgopolov

.model small
.stack 100h

code segment public        ; Start of the code segment
    assume cs:code

    main proc              ; Start of the main procedure
        mov     al, 11h    ; Copy the value 17h into the al register
        mov     bl, 22h    ; Copy the value 34h into the bl register
        xchg    al, bl     ; Exchange the contents of al and bl

        mov     ax, 4C00h  ; Copy the process termination function number into ah and the value into al
        int     21h        ; Call the interrupt
    main endp              ; End of the main procedure

code ends                  ; End of the code segment
end main                   ; End of file. The main procedure is the entry point

Example taken from the textbook "HANDYFAR - MASM (Evgeny Sergeevich Dovgopolov)".

Processor status flags

CF
No
PF
No
AF
No
ZF
No
SF
No
TF
No
IF
No
DF
No
OF
No