Angel Politis
Angel Politis

Reputation: 11313

Output of Assembly code - Confusion with add?

I just started learning Assembly and in one exercise I have to find the output of the following code, but since I'm very new, I'm not sure what it is and that's mainly because of add.

Assembly Code:

addi $8, $0, 0     # $8 = $0 + 0 = 0 + 0 = 0
addi $9, $0, 8     # $9 = $0 + 8 = 0 + 8 = 8
L1:
    add $4, $0, $8      # $4 = $0 + $8 = $8
    addi $2, $0, 1     # $2 = $0 + 1 = 0 + 1 = 1
    addi $8, $8, 1     # $8 = $8 + 1
    syscall     # show the number in $4 
bne $8, $9, L1     # if $8 ≠ $9 go to L1 (line 3)

The way I look at it, the above code should output the numbers 0-7, but since I'm new to Assembly, I thought of translating the code to C++ to figure it out, but in C++ I got 1-8, because I was inclined to translate add $4, $0, $8 as $4 = &$8.

C++ Code:

#include <iostream>
using namespace std;

int main() {
  int $0 = 0, $2, $8, $9, *$4;

  $8 = $0 + 0;      // $8 = 0
  $9 = $0 + 8;      // $9 = 8

  do {
    $4 = &$8;
    $2 = $0 + 1;
    $8 = $8 + 1;
    cout << *$4 << endl;
  }
  while ($8 != $9);
  return 0;
}

Question: Is Assembly's add $4, $0, $8 to be thought of as $4 being a pointer to $8 or simply equal to what $8 is at the time. (The confusion has been created by the comment next to add).

Upvotes: 2

Views: 186

Answers (2)

dave
dave

Reputation: 4922

As mentioned by Zach your C++ code is setting $4 to the value of the address of $8 but the assembly is setting the value of $4 to $8. Thus the correct C++ code is below. What it prints out is left as an exercise!

Additionally $2 is just set for the syscall, so we don't need it in our C++ code: I've removed it to get rid of the "unused variable" warning.

#include <iostream>
using namespace std;

int main() {
  int $0 = 0, $8, $9, $4;

  $8 = $0 + 0;      // $8 = 0
  $9 = $0 + 8;      // $9 = 8

  do {
    $4 = $8;
    $8 = $8 + 1;
    cout << $4 << endl;
  }
  while ($8 != $9);
  return 0;
}

Upvotes: 2

Zach Zundel
Zach Zundel

Reputation: 415

You are setting the value of $4 to the value of $8, whatever it is when that instruction is executed. Your code is saying that since you are adding the value of $8 to $0, it is the same as just loading the value of $8 into $4.

Note, you can accomplish the same thing by using move $4 $8.

Upvotes: 2

Related Questions