0

So, how can you write the following in assembly:

do{
   //do something
}while (x<1000 || x>9999);

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
jsnjdhs
  • 23
  • 7

1 Answers1

2

In assembly language, we use "if-goto-label" style for control structures (if-then, if-then-else, for, while, do-while etc..).  This form quite easy & natural in assembly/machine code — its called a conditional branch, and all processors have some form for it.  The C construct

if ( condition ) goto label;

corresponds to conditional branching in assembly language.  And C also has the simple goto label; alone without the surrounding if, which is called unconditional branching in assembly language, and all processors also have some form of it.


For a do-while loop in C,

...
do {
    .. do something ..
} while ( condition );
...

The "if-goto-label" pattern is:

    ...
Loop1:
    .. do something ..
    if ( condition ) goto Loop1;
    ...

In your case, the condition is disjunctive, either condition should continue the loop.

Given condition1 || condition2 for the do-while condition:

    ...
Loop1:
    .. do something ..
    if ( condition1 ) goto Loop1;
    if ( condition2 ) goto Loop1;
    ...

In the above, the || is handle by testing one condition, then the other.  If the first condition is true, it loops without testing the second condition.  If first condition is false, it proceeds on to test the second condition, which will then determine whether to loop or go on to the next statement after the loop.

This translates quite easily into assembly language.  All processors provide some kind of conditional branch, maybe as one single instruction, maybe as a 2 instruction pair, as in a compare & branch sequence.  Conditional branches are used more-or-less directly to implement any one if-condition-goto statement.

Erik Eidt
  • 23,049
  • 2
  • 29
  • 53
  • In this case, the condition can be optimized to one range-check. Like [double condition checking in assembly](https://stackoverflow.com/a/5197264) (x86 example, but the same logic works everywhere) – Peter Cordes Nov 17 '20 at 19:12
  • And let's also note that we can also substitute `|` for `||`, which is often also a good optimization. – Erik Eidt Nov 17 '20 at 19:33
  • Yes, especially on MIPS where you often have to materialize conditions as boolean vars in registers. Or on 32-bit ARM where `cmp` / predicated-`cmp` can often chain 2 conditions with zero overhead. – Peter Cordes Nov 17 '20 at 19:58