typestar

cmov in Assembly

Pick a value from flags without branching.

; cmov picks a value from flags without a branch.
        global _start

        section .text
_start:
        mov rax, 88             ; candidate a
        mov rbx, 19             ; candidate b

        cmp rax, rbx
        cmovl rax, rbx          ; if a < b, take b: branch-free min/max

        mov rdx, 100
        cmp rax, rdx
        cmovg rax, rdx          ; clamp to 100

        mov rdi, rax            ; max(88,19) clamped = 88
        mov rax, 60             ; exit code 88
        syscall

How it works

  1. cmovl moves only if the compare said less-than.
  2. A second cmov clamps against an upper bound.
  3. Branch-free min, max, and clamp are all this shape.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
404
Tokens
49
Three-star pace
55 tpm

At the three-star pace of 55 tokens a minute, this run takes about 53 seconds.

Type this snippet

Step 4 of 4 in Bits & flags, step 18 of 31 in Language basics.

← Previous Next →