Implementing Arithmetic Expressions


This program implements the following C++ expression in assembly language, using 32-bit signed integers:

x = ( y / z ) × ( x + y )
 INCLUDE Irvine32.inc
 .data
   x  SDWORD  ?
   y  SDWORD  ?
   z  SDWORD  ?
   prompt1  BYTE  "x = ", 0
   prompt2  BYTE  "y = ", 0
   prompt3  BYTE  "z = ", 0
   prompt4  BYTE  0Dh, 0Ah, "( y / z ) * ( x + y ) = ", 0
   prompt5  BYTE  0Dh, 0Ah, "Divide by zero!", 0Dh, 0Ah, 0
   prompt6  BYTE  0Dh, 0Ah, "Overflow!", 0Dh, 0Ah, 0
 .code
 main PROC
   ;; Read x.
   mov   edx, OFFSET prompt1
   call  WriteString
   call  ReadInt
   mov   x, eax

   ;; Read y.
   mov   edx, OFFSET prompt2
   call  WriteString
   call  ReadInt
   mov   y, eax

   ;; Read z.
   mov   edx, OFFSET prompt3
   call  WriteString
   call  ReadInt
   mov   z, eax
   ;; Calculate x = ( y / z ) × ( x + y ) .
   mov   eax, y
   cdq
   test  z, 0FFFFFFFFh
   jz    ZERO
   idiv  z
   mov   ebx, x
   add   ebx, y
 

 
     
mov x, eax ;; Print result. mov edx, OFFSET prompt4 call WriteString mov eax, x call WriteInt call Crlf exit
 ZERO:   ;; Divide by zero.
   mov   edx, OFFSET prompt5
   call  WriteString
   exit

 OVERFLOW: ;; Result is too large.
   mov   edx, OFFSET prompt6
   call  WriteString
   exit
 main ENDP
 END main
An Execution Example
  x =   7 
  y =  18 
  z =   3 
  
  ( y / z ) * ( x + y ) = +150

The italic white text with navy background is entered by users.




      “I’m not arguing, I’m just explaining why I’m right.”    
      ― Unknown