3

I'm using a language called Jack, as part of the Nand2Tetris course.

This compiles and produces the output I expect when run:

class Main {
    function void main() {
        var Foo f;
        do f.doSomething();
        return;
    }
}

class Foo {
    method void doSomething() {
        do Output.printString("Hello, world!");
        return;
    }
}

But when I add a line...

class Main {
    function void main() {
        var Foo f;
        do f.doSomething();

        var int i; // doesn't seem to matter what's here, anything breaks it

        return;
    }
}

...I get this compiler error:

In Main.jack (line 6): In subroutine main: Expected statement(do, let, while, return, or if)

Why does the additional line make a difference?

Andrew Cheong
  • 29,362
  • 15
  • 90
  • 145

1 Answers1

4

There are programming languages that are more structured than others. Jack seems to be very strict when it comes to places where you are allowed to declare variables.

Following Jack presentation you provided:

subroutine_type name (parameter-list) {
    local variable declarations
    statements
}

Moving variable i declaration to where it belongs should fix you problem.

class Main {
    function void main() {
        var Foo f;
        var int i;
        do f.doSomething();

        return;
    }
} 
zubergu
  • 3,646
  • 3
  • 25
  • 38
  • Slide 26 of the PDF, if anyone else is searching for it. – Andrew Cheong Apr 27 '16 at 22:53
  • To be clear, the issue is that all the local variable declarations need to come before statements. Slide 26 of the PDF shows the order that the code needs to be written. The reason why Jack is so structured is to make the subsequent writing of the compiler as easy as possible. – Adam Zerner Jan 02 '17 at 20:41