Nand To Tetris (Jack): Simple if conditional with equality testing giving this error - "Expected - or ~ or ( in term"

1.3k views Asked by At
class Main {
  function void main() {
    var String foo;
    let foo = "bar";

    if (foo == "bar") {
      do Output.printString("true");
    }
    else {
      do Output.printString("false");
    }

    return;
  }
}

I get the error: Expected - or ~ or ( in term.

Full output:

code/nand2tetris » tools/JackCompiler.sh projects/09/Test
Compiling /Users/adamzerner/code/nand2tetris/projects/09/Test
In Main.jack (line 6): In subroutine main: Expected - or ~ or ( in term
code/nand2tetris »

What does the error mean?

1

There are 1 answers

0
Adam Zerner On BEST ANSWER

The issue is that I used == instead of =. In Jack, equality is tested for using a single equals rather than a double or triple (double/triple equals is conventional in other languages).

See bullet point 7 in slide 22 of the Chapter 9 PDF for documentation saying that equality comparison is done with a single equals.

See SquareGame.jack line 40 in the course software for an example.

The following code compiles without error. It doesn't give the expected output, but the reason for that is a separate topic.

class Main {
  function void main() {
    var String foo;
    let foo = "bar";

    if (foo = "bar") {
      do Output.printString("true");
    }
    else {
      do Output.printString("false");
    }

    return;
  }
}