Unreachable code in a program using KeyPressed

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

Unreachable code in a program using KeyPressed

Ichiro
Hi,

I am writing a code to output a value from the keyPressed() function on the screen. I referred to a sample code of the SquareGame.jack and the following is my code.  The error message "Unreachable code" appeared for the last while part.

Could you tell me any clue as to why this happened?


class Main {
     function void main() {
      var int key;
      while(true){
        while (key=0){
          let key=Keyboard.keyPressed();
          do Output.printString("wait for the button to be pressed");
          return;
        }
        while (~(key=0)){          #Unreachable code
          let key=Keyboard.keyPressed();
          do Output.printInt(key);
          return;
        }
      }
   }
}


Also, I have a question about an expression of while in the sample SquareGame code, which is written as "(~exit)". Why not simply writing "true"?

 while (~exit) {
         // waits for a key to be pressed
         while (key = 0) {
            let key = Keyboard.keyPressed();
            do moveSquare();
         }

Thanks,
Ichiro

Reply | Threaded
Open this post in threaded view
|

Re: Unreachable code in a program using KeyPressed

WBahn
Administrator
What tool is telling you that the code is unreachable? The supplied Jack compiler? I wouldn't think that it was that sophisticated.

The reason, however, is that the Jack language specification requires that local variables be initialized to zero. That means that 'key' will start out as zero, which means that the first while loop WILL run, and that loop's body ends with a return statement.

As for the second question, you haven't shown the entire while() loop body. I'm assuming that there's a statement somewhere in it that has the ability to change the value of 'exit'.
Reply | Threaded
Open this post in threaded view
|

Re: Unreachable code in a program using KeyPressed

Ichiro
The message was supplied by Jack compiler. I understand why the message was issued thanks to your explanation. I did not understand what the "return" does in the command.

As you assumed, I found the statement to change the value of 'exit' to true in the following code.

Thanks,
Ichiro