Utis
Utis

Reputation: 21

How can I return from the label to the loop? | TASM

I need the sum of numbers that are less than N, I created a loop and a condition. When the condition is met, we get into the label, however, it does not work to return from it. What should I do?

mov     [Sum],  0
        mov     cx,     [N]
        mov     ax,     1
        ForI:

                cmp ax, 10
                jl check
                ;add     [Sum],  ax
                inc     ax

        loop    ForI

        check:
            add [Sum], ax

Upvotes: 0

Views: 327

Answers (1)

Erik Eidt
Erik Eidt

Reputation: 26656

What I suggest is a simple pattern matching approach to translating control structures of structured statements.  What you're trying to accomplish is an if-statement nested within a loop, such as this:

ctr = N;
val = 0;
do {
   if ( val >= 10 )
       sum += val;
   val++;
} while ( --ctr >= 0 );

A do-while-loop has a structured statement pattern of the following:

do
    <loop-body>
while ( <condition> );

and the equivalent pattern in assembly language's if-goto-label style is:

Loop1:
    <loop-body>
    if ( <condition> ) goto Loop1;

An if-then structured statement has the following pattern:

if ( <condition> )
    <then-part>

The equivalent in assembly's if-goto-label style is:

    if ( <condition> is false ) goto EndIf1;
    <then-part>
EndIf1:

So, just put these two patterns together and your code will work the same as that C pseudo code.  These patterns keep the various parts of the structured statements in the same orientation, so if you put something in the wrong place it should be clear.

ctr = N;
val = 0;
do {
   if ( val >= 10 )               // <loop-body> starts here (inclusive)
       sum += val;                // <loop-body>
   val++;                         // <loop-body> ends here (inclusive)
} while ( --ctr >= 0 );

So, what you want the assembly code to look like is the do-while-loop pattern and then nested entirely within it as the loop-body is a compound statement (i.e. sequential statements) with one if- and one increment statement.  Translate the if-statement, nesting it in the same place as it appears in the loop-body of the do-while statement, and do the same with the val++; — locating it after the complete if-statement pattern and both together as the loop-body that is nested fully within the do-while loop as I've shown in C above.


There are other approaches that are easy for experienced assembly programmers (but error prone for beginners).  For example, you could fix the code in your post by adding some goto's (jmp) in the right places, but that won't necessarily teach you the concept of nested and sequential control structures using structured statements and how they related to the if-goto-label form.

The pattern match & translate approach will be less error prone the more code you have to translate, like doubly nested loops and such.

Upvotes: 3

Related Questions