enum Foo {
bar,
baz,
}
By just simply looking at this code, I thought it would print bar, baz
and then barr, bazz
void main() {
final f = Foo.bar;
switch (f) {
case Foo.bar:
case Foo.baz:
print("bar, baz");
}
switch (f) {
case Foo.bar:
if (false) {
return;
}
case Foo.baz:
print("barr, bazz");
}
}
It seems obvious right ? if (false) is never called, so it won't return, it will fall to the next switch case.
But no . It prints bar, baz
What are the two code block not equivalent ? What is the design choice behind this and how does it compare to other languages. Or this is just Yet another Dart bug
Update:
I tested it JS, JS works the way I thought. Not dart
let day;
switch (0) {
case 0:
if (false) {
break;
}
case 1:
case 2:
day = "Tuesday"; // prints this
break;
case 3:
day = "Wednesday";
break;
}
Once you have assigned a code to be executed to some case
, it's not necessary to break from switch
, for example look at the following code:
int x = 0;
switch (x) {
case 0:
print('0');
case 1:
print('1');
}
The output is just 0
, the case of 1
didn't get executed, the execution has break the switch after matching some case.
When the value matches a case's pattern, the case body executes. Non-empty case clauses jump to the end of the switch after completion. They do not require a break statement. Other valid ways to end a non-empty case clause are a continue, throw, or return statement.
But
Empty cases fall through to the next case, allowing cases to share a body.
So, for your question's second switch statement:
switch (f) {
case Foo.bar:
if (false) { // you have some code to do
return;
}
case Foo.baz:
print("barr, bazz");
}
you have assigned some code to be executed in case of Foo.bar
, doesn't matter whether it's a dead code or not, it's still a code to be executed in case of match.
Match is found, but you didn't do anything if(false)
never get executed, then the switch statement is over.
And for your JS code, JS like other languages C++, JAVA: you must explicitly write a break
to break from switch statement.
So, for case 0
it has a code to be executed, but break statement nested inside if(false) never seen, so execution go through the down cases until break
is found.
for more info dart branches