Sikau

Assembly language · Day 10 · about 40 min

From C to assembly

How for-loops, ifs, arrays and early returns compile — by translating one yourself.

Be the compiler

A compiler turns each high-level construct into a pattern you already know: variables become registers, a[i] becomes base + i × 4 and a load, for becomes a test, a body and a jump back, and return becomes "put it in a0 and ret".

int index_of(int *a, int n, int x) {
  for (int i = 0; i < n; i++) {
    if (a[i] == x) return i;
  }
  return -1;
}

Line by line

.data
nums: .word 4, 8, 15, 16, 23, 42

.text
# index_of(a0 = address, a1 = n, a2 = x) -> index of x, or -1
index_of:
  li   t0, 0                # i = 0
io_loop:
  bge  t0, a1, io_none      # i < n ?
  slli t1, t0, 2
  add  t1, a0, t1
  lw   t2, 0(t1)            # a[i]
  beq  t2, a2, io_found     # a[i] == x  ->  return i
  addi t0, t0, 1            # i++
  j    io_loop
io_found:
  mv   a0, t0
  ret
io_none:
  li   a0, -1
  ret

The rest of this lesson

  • A map from C to registersexplain
  • The early returnexplain
  • Translate the looporder
  • C construct to assemblymatch
  • Your translationwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 12 lessons of Assembly language