Users › 04 Control flow
All the statements, including the two details that surprise
newcomers: switch falls through, and statements end at newlines.
if (cond) { ... } else if (cond2) { ... } else { ... }
while (cond) { ... }
do { ... } while (cond)
for (init; cond; update) { ... } // there is no for-in
break / continue / return [value]
Conditions must be bool; there are no truthy values.
for is the C form only. There is no loop else, no
labels, no goto.
switch (x) {
case 1:
...
break
case 2:
case 3: // fallthrough, like C
...
break
default:
...
}
byte, short,
int, long); cases are integer literals.break and execution
continues into the next case.Statements end at a newline. A semicolon also works, and newlines inside
parentheses are ignored. The parser is lenient about adjacent statements
(int x = 1 int y = 2 parses), but you should still write one
statement per line.
%simple com.example.flow.FizzBuzz implements Main
#import Std
int run(int argc, String[] argv) Main@run {
int i = 1
while (i <= 15) {
if (i % 15 == 0) {
Std.print("FizzBuzz\n")
} else if (i % 3 == 0) {
Std.print("Fizz\n")
} else if (i % 5 == 0) {
Std.print("Buzz\n")
} else {
Std.print(i, "\n")
}
i = i + 1
}
return 0
}
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
%simple com.example.flow.SwitchDemo implements Main
#import Std
int run(int argc, String[] argv) Main@run {
int i = 0
while (i < 4) {
switch (i) {
case 0:
Std.print("zero\n")
break
case 1:
case 2:
Std.print("one or two\n")
break
default:
Std.print("many\n")
}
i = i + 1
}
return 0
}
zero
one or two
one or two
many