Memory Operands in Other Instructions (add, etc.)

From MediaWiki
Revision as of 14:46, 20 October 2025 by Bfh-sts (talk | contribs) (Created page with "= Arithmetic: add, sub, inc, dec = This page explains basic arithmetic instructions in x86-64 assembly language, including addition, subtraction, increment, and decrement. == Overview == Arithmetic instructions modify register or memory contents. Most of them follow this general pattern: instruction destination, source The result is stored in the destination operand. == Addition (add) == Adds the source value to the destination and stores the result in the destinat...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Arithmetic: add, sub, inc, dec

This page explains basic arithmetic instructions in x86-64 assembly language, including addition, subtraction, increment, and decrement.

Overview

Arithmetic instructions modify register or memory contents. Most of them follow this general pattern:

instruction destination, source

The result is stored in the destination operand.

Addition (add)

Adds the source value to the destination and stores the result in the destination.

Syntax:

add destination, source

Examples:

add rax, rbx      ; rax = rax + rbx
add r10, 4        ; r10 = r10 + 4
add [rcx], rdx    ; memory at rcx = memory[rcx] + rdx

The instruction affects several CPU flags:

  • CF (Carry Flag) – set if result exceeds register size.
  • ZF (Zero Flag) – set if result is 0.
  • SF (Sign Flag) – set if result is negative.
  • OF (Overflow Flag) – set if signed overflow occurs.

Subtraction (sub)

Subtracts the source value from the destination and stores the result in the destination.

Syntax:

sub destination, source

Examples:

sub rax, 1        ; rax = rax - 1
sub [rbx], rcx    ; memory[rbx] = memory[rbx] - rcx

Like add, sub modifies the condition flags.

Increment (inc) and Decrement (dec)

These are special cases of add and sub that modify the operand by 1.

Examples:

mov eax, 0xFFFFFFFF
inc eax           ; eax becomes 0, sets ZF, PF, AF
mov ebx, 0x2D
dec ebx           ; ebx becomes 0x2C, clears most flags

Usage:

  • inc increases by 1 → useful for counters and loops.
  • dec decreases by 1 → useful for iteration and countdowns.

Example: simple loop

mov ecx, 5

loop_start:

dec ecx
jnz loop_start     ; continue looping until ecx = 0

This uses dec and the Zero Flag (ZF) to control the loop.

Notes on performance

While add/sub and inc/dec behave similarly, inc and dec do not modify the Carry Flag (CF). For arithmetic where CF matters (e.g., multiword addition), use add/sub instead.