assemblyhla

Trying to convert if-else conditional to Assembly?


How can I convert this to assembly language? if((w == x)&&(x == y)&&(y == z)&&(z == w)) into HLA form with series of cmp and jmp command?

here my command so far:

program same;
#include("stdlib.hhf");
procedure theSame(w:int16; x:int16; y:int16; z:int16); @nodisplay; @noframe;

begin theSame;
*if((w == x)&&(x == y)&&(y == z)&&(z == w))*
mov(1, AL);
stdout.put("Same.", nl);
else
mov(0, AL);
stdout.put("Not the same", nl);
endif;
stdout.put("AL: ", (type int16 AL), nl);
end theSame;

begin sameOrnot;
stdout.put("Feed Me W: ");
stdin.get(w);
stdout.put("Feed Me X: ");
stdin.get(x);
stdout.put("Feed Me Y: ");
stdin.get(y);
stdout.put("Feed Me Z: ");
stdin.get(z);
theSame(w, x, y, z);
end sameOrnot;

Solution

  • if((w == x)&&(x == y)&&(y == z)&&(z == w))
    

    Unlike the bitwise & operator, && guarantees left-to-right evaluation. So if (w == x) evaluates to false, no further evaluation is needed

      mov ax, w      ; (w == x)
      cmp ax, x
      jne IsFalse
      mov ax, x      ; &&(x == y)
      cmp ax, y
      jne IsFalse
      mov ax, y      ; &&(y == z)
      cmp ax, z
      jne IsFalse
      mov ax, z      ; &&(z == w)
      cmp ax, w
      jne IsFalse
    IsTrue:
      ...
    IsFalse:
      ...
    

    The &&(z == w) part is redundant! Because of the guaranteed left-to-right evaluation, by the time we arrive at the 4th part, we already know that w EQ x EQ y EQ z. Associativity dictates that w EQ z.

    We can also refrain from reloading the AX register because of the equality we got from each previous step.

      mov ax, w      ; (w == x)
      cmp ax, x
      jne IsFalse
                     ; AX already holds the value for x (same as w)
      cmp ax, y      ; &&(x == y)
      jne IsFalse
                     ; AX already holds the value for y (same as w)
      cmp ax, z      ; &&(y == z)
      jne IsFalse
    IsTrue:
      ...
    IsFalse:
      ...