How do I perform a while loop in assembly code?

I'm just learning assembly code and I am not understanding how loops work very well.

I made the following program to print a few letters in the alphabet and it just keeps printing everything in the ASCII table over and over again until I terminate it with ctrl+c, but I'm not sure why. when I switch the values 'a' and 'b' it doesn't loop at all:

.section .data

msg: .ascii "A"

len: .int 1

a: .int 1

b: .int 5

.section .text

.global _start

_start:

mov len, %edx

mov $msg, %ecx

mov $4, %eax

mov $1, %ebx

int $0x80

loop_begin:

mov a, %eax

mov b, %ebx

cmp %ebx, %eax

jge loop_end

movb (msg), %al

incb %al

movb %al, (msg)

mov $4, %eax

mov $1, %ebx

int $0x80

inc %eax

jmp loop_begin

loop_end:

mov $0, %ebx

mov $1, %eax

int $0x80

Update:

I see that I am am just comparing 1 and 5 each time :s I was attempting to use a: .int1 as a counter by using inc %eax at the end of the loop... but I guess it just reinserts the value of 1 at each iteration of the loop?

How can I implement a working counter variable in assembly for this program?

4 Answers

Relevance
  • Ilie
    Lv 5
    8 years ago
    Best Answer

    Hi,

    The bug can be resolved by moving the label after the loop initialization code, as such:

    mov a, %eax

    mov b, %ebx

    loop_begin:

    cmp %ebx, %eax

    jge loop_end

    There's another bug there as well. You are writing over your counter register when you try to set up the INT 80h call. This can be fixed the following way:

    push %eax

    mov $4, %eax

    mov $1, %ebx

    int $0x80

    pop %eax

    Cheers,

    Bogdan

  • 8 years ago

    You keep comparing 1 to 5, rather than comparing something that changes inside the loop.

    Update: These two lines are the problem:

    mov a, %eax

    mov b, %ebx

    Those overwrite the value you are incrementing.

  • Elana
    Lv 7
    8 years ago

    Assembly for what computer? x86? Sparc? Vax? PDP-11?

    In any case, in all cases they will be:

    top_of_loop:

    If_some_condition_skip

    jump_to_end_of_loop

    (body of loop)

    jump_to_top_of_loop

    end_of_loop:

  • 3 years ago

    I do not think that's accurate

Still have questions? Get your answers by asking now.