# `xchg`

[x86-64 Documentation](https://asm-editor.specy.app/documentation/x86.md) › [Instructions](https://asm-editor.specy.app/documentation/x86/instruction.md)

Web page: https://asm-editor.specy.app/documentation/x86/instruction/xchg

**Exchange register/memory with register**

Category: Data movement

Exchanges the values of its two operands.

8086 and later

[Intel's reference: XCHG](https://intel.github.io/SDM/instruction/XCHG.html)

## Flags

| Flag | Effect |
| --- | --- |
| CF | not changed |
| PF | not changed |
| AF | not changed |
| ZF | not changed |
| SF | not changed |
| DF | not changed |
| OF | not changed |

## Forms

- `xchg reg, r/m` (8, 16, 32, 64) · accepts the `lock` prefix with a memory operand
  - `xchg reg8, r/m8`
  - `xchg reg16, r/m16`
  - `xchg reg32, r/m32`: 386 and later
  - `xchg reg64, r/m64`
- `xchg r/m, reg` (8, 16, 32, 64) · accepts the `lock` prefix with a memory operand
  - `xchg r/m8, reg8`
  - `xchg r/m16, reg16`
  - `xchg r/m32, reg32`: 386 and later
  - `xchg r/m64, reg64`
- `xchg acc, reg` (16, 32, 64)
  - `xchg ax, reg16`
  - `xchg rax, reg64`
  - `xchg eax, reg32na`: 386 and later
- `xchg reg, acc` (16, 32, 64)
  - `xchg reg16, ax`
  - `xchg reg64, rax`
  - `xchg reg32na, eax`: 386 and later

## Operands

- `reg`: A general-purpose register matching the operation’s size, for example `al`, `ax`, `eax` or `rax`.
- `r/m`: A general-purpose register or memory location matching the operation’s size, for example `rax` or `qword [rbp-8]`.
- `acc`: The accumulator: `al`, `ax`, `eax` or `rax`, whichever matches the operation’s size. The form accepts no other register in this position.

## Description

When one of them is in memory, the exchange is always atomic, `lock` prefix or not, so `xchg` with memory is a ready-made synchronisation primitive, and slower than an ordinary move for that reason. A `lock` prefix on an exchange of two registers raises an invalid-opcode fault.

In 64-bit code a 32-bit exchange clears the upper halves of both 64-bit registers, `xchg eax, eax` included: NASM assembles that as a real exchange rather than as `90h`, which in 64-bit mode is always a [`nop`](https://asm-editor.specy.app/documentation/x86/instruction/nop.md).

## Example

```x86
global _start

section .text
_start:
        mov rax, 12
        mov rbx, 5
        mov rcx, 3
        mov rsi, 9

        xchg rax, rbx

        mov rax, 60         ; syscall 60: exit
        xor rdi, rdi
        syscall
```
