Ways of implementing an infinite loop in project 4

classic Classic list List threaded Threaded
5 messages Options
Reply | Threaded
Open this post in threaded view
|

Ways of implementing an infinite loop in project 4

sunnysideup
Hi I've learned in the lecture that we should end instructions with an infinite loop like this

(END)
    @END
    0;JMP

but while doing the project, I came to wonder if I could just omit the @END line like below,
since the A register will always be set to @END anyways,

(END)
    0;JMP

it works when I run the emulator but I'm curious whether this could lead to any potential problems?
thank you for your help!
Reply | Threaded
Open this post in threaded view
|

Re: Ways of implementing an infinite loop in project 4

ivant
This post was updated on .
Why do you think that A register will always be set to END's address?

[EDIT] Here is an example program to consider:

@235
(END)
    0;JMP 
Reply | Threaded
Open this post in threaded view
|

Re: Ways of implementing an infinite loop in project 4

sunnysideup
in my code I only get to END if some conditions are met, like this

1     @END
2     D;JEQ

3 (END)
4     @END
5     0;JMP

so I assumed that since the A register would always be set to END before jumping in line 2,
this could be left out in line 4 and still have the infinite loop going.

But I'm really new to everything so I thought that there could be exceptions that I couldn't think of.
It'd be great if someone could tell me a case that would be problematic!

Reply | Threaded
Open this post in threaded view
|

Re: Ways of implementing an infinite loop in project 4

ivant
Ah, I see. It is good to think like that, because it gives you deeper understanding of how things work and why are they written in certain way.

The code snippet
(END)
    @END
    0;JMP
works for all cases. There are cases where you can skip the @END, but then your code will be more "brittle". that is, it can break if you change something unrelated, because it assumes that the value in A is the correct one. And if that happens, the behavior of your program will be quite unpredictable and hard to diagnose.

We can write this in the following way instead:
(END)
    @END_INFINITE
(END_INFINITE)
    0;JMP
This way we're setting A only once. And it's still just 2 instructions, because the labels aren't instructions. But then again, why would we want to optimize a NOP infinite loop?
Reply | Threaded
Open this post in threaded view
|

Re: Ways of implementing an infinite loop in project 4

sunnysideup
wow thank you for the detailed explanation, now I see why the original one is better!