ASSEMBLY / CHAPTER 09
Bounded loops over arrays
MasterTranslate an explicit array contract into a correct machine-level loop.
By the end of this chapter
- Check the bound before each access
- Handle empty input without dereferencing
- Connect address scaling to element size
The idea
Enter with addressing and unsigned branches understood. A safe conceptual array loop needs a base address, a count, an index, and an explicit bound test. For this chapter, the count is a nonnegative unsigned size and the base points to that many readable dwords. When the count is zero, no memory access is permitted or needed. Assembly will not enforce this contract for you.
Place the bound check before the load so the empty case naturally skips the body. An index below count selects a valid element, and multiplying it by four produces its byte offset. Advance exactly once per iteration. The example accumulates with thirty-two-bit arithmetic, so its general result is modulo two to the thirty-second power; the small sample does not overflow.
; RDI points to dwords 2, 4, 6; RSI = 3
xor eax, eax
xor ecx, ecx
.loop:
cmp rcx, rsi
jae .done
add eax, [rdi+rcx*4]
inc rcx
jmp .loop
.done:Final EAX = 12 and RCX = 3; no console output.
The precheck admits indices zero, one, and two. Index three exits before an out-of-bounds access.
Try it yourself
Adapt the loop to count zero-valued elements instead of summing them.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING