Skip to content

Instantly share code, notes, and snippets.

@rcdilorenzo
Last active August 7, 2021 18:51
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rcdilorenzo/dfe2714a61608f1e6f44 to your computer and use it in GitHub Desktop.
Save rcdilorenzo/dfe2714a61608f1e6f44 to your computer and use it in GitHub Desktop.
Creating a MASM loop with the condition either above or below the block to execute (e.g. a while vs do..while loop in C)
; Description:
; This program demonstrates how to
; create a while-style loop with the
; condition either above or below
; the block of code to execute.
; Author: Christian Di Lorenzo
INCLUDE Irvine32.inc
.data
n BYTE 10
.code
main PROC
; Method 1: Pre-test condition
xor eax, eax ; clear EAX register
movzx ecx, n ; track how many times to loop
Loop1:
cmp ecx, 0 ; check if done looping
je EndLoop1 ; jump outside of loop if done
add eax, ecx ; [Loop] sum first ecx integers
dec ecx ; [Loop] decrement counter
jmp Loop1 ; jump to beginning of loop
EndLoop1:
call DumpRegs
; Method 2: Post-test condition
xor eax, eax ; clear EAX register
movzx ecx, n ; track how many times to loop
jmp TestCondition ; jump immediately to bottom for checking condition
Loop2:
add eax, ecx ; [Loop] sum first ecx integers
dec ecx ; [Loop] decrement counter
TestCondition:
cmp ecx, 0 ; check if done looping
jne Loop2 ; jump to beginning of loop if not done
EndLoop:
call DumpRegs
exit
main ENDP
END main
@developer-juice
Copy link

even though in the loop2 you only used the Loop2 label in a jump statement, it was helpful to see testcondition and endloop labels written explicitely too.

@rcdilorenzo
Copy link
Author

Excellent, @developer-juice. Glad it was helpful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment