Author Topic: NASM loop  (Read 20962 times)

Offline 1mihcc

  • New Member
  • Posts: 1
NASM loop
« on: November 15, 2015, 04:57:13 PM »
Hi guys,

I am new to assembly and NASM. I am trying to write program, that outputs numbers form 1 to N. I am using scanf function from language C to read input value N. I am writing in SASM for windows.
I have trouble to begin, because i don`t know how to create loop in NASM.

Thanks.

Offline Frank Kotler

  • NASM Developer
  • Hero Member
  • *****
  • Posts: 2667
  • Country: us
Re: NASM loop
« Reply #1 on: November 15, 2015, 06:39:10 PM »
The "loop" instruction is easy. It uses ecx (or cx in 16-bit code):
Code: [Select]
mov ecx, 10
top:
; do some stuff
loop top
However... The "loop" instruction on the AMD K6-2 (?) was too fast and broke the installer on Win95 (?) so it was deliberately showed down - it's still a small instruction, but no longer fast. (that's the story I heard anyway) Worse, ecx is one of the registers that the C library (among other things) is allowed to alter. This has caused many problems for beginners on exactly the program you want to write!

So you probably want to use some register the C library won't alter...
Code: [Select]
mov esi, 10
top:
; do some stuff
dec esi
jnz top
This is what "loop" does, without using ecx. (as an alternative, you can save ecx around calls to C)

When using "scanf" (lemme see, you're in Windows, so you spell it _scanf),  the parameter is an address to put the number, not the number itself (K&R calls this "the most common error"). _scanf does return a value in eax, but it is the number of items read, not the number you're looking for! See how you do with those clues... Come back if you need more help.

Best,
Frank