------------------------------------------------------------------------------
MC logo
Alternate Counter
[^] 386 Assembler Language
------------------------------------------------------------------------------
[Chapter 1: Introduction] [Chapter 2: Data Representation] [Chapter 3: Boolean Algebra and Digital Logic] [Chapter 4: MARIE: A Very Simple Architecture] [386 Assembler Language] [Chapter 5: Real-World Architectures] [Chapter 6: Memory Systems] [Chapter 7: I/O Systems] [Chapter 9: Alternative Architecture] [Chapter 11: Performance Measurement]
[Hello, World!] [Counter] [Alternate Counter] [Max of Three]
count2.s
;;; This program reads an integer limit then counts from 1 to the limt.
;;; Uses plain C I/O and must be linked to the C libraries.
;;; This version differs from count.s in that it keeps its data on the stack.
        global  main
        extern  printf
        extern  scanf

        section .text
main:
        ;; Frame pointer
        push    ebp
        mov     ebp,esp

        ;; Make space on the stack for the limit (ebp-4) and the
        ;; loop count (ebp-8)
        sub     esp,8

        ;;  Issue the prompt using printf.
        push    prompt
        call    printf
        add     esp,4

        ;; Read the value using scanf.
        lea     eax, [ebp-4]    ; EAX gets the address ebp-4.
        push    eax             ; Put it onto the stack
        push    rfmt            ; Other args and call.
        call    scanf
        add     esp,8

        ;; Init the counter.  The modifier dword specifies a 32-bit 1, and
        ;; is needed here because the assembler cannot otherwise determine
        ;; the intended size.
        mov     [ebp-8],dword 1
        
        ;; Loop test.  Get the counter to eax, then compare to the limit.
ltop:   mov     eax,[ebp-8]     ; Counter
        cmp     eax,[ebp-4]     ; Limit
        jg      finish

        ;; Print count.  Use count value still in eax.
        push    eax
        push    pfmt
        call    printf
        add     esp,8

        ;;      Increment the count
        inc     dword [ebp-8]
        
        ;;  Back to the top
        jmp     ltop

        ;; Pop the workspace off the stack, fix up frame pointer, leave.
finish: add     esp,8

        mov     esp,ebp
        pop     ebp

        ret

        section .data
prompt: db      'Enter count: ',0
rfmt:   db      '%d',0
pfmt:   db      ' => %d',10,0