Acknowledged

continue in a switch statement behaves surprisingly

I had a switch statement inside a loop, and expected that continue would go to the next iteration of the loop. But instead, it restarts the switch. This might actually be useful behavior, and I seem to remember at least one other language that did something similar with switch statements. The only problem is that it restarts the switch with exactly the same value as the first time through.

So with this code:

function foo(x as Number) as Void {
  switch (x) {
    case 1:
      System.println("one");
      x++;
      continue;
    case 2:
      System.println("two");
      x++;
      continue;
    case 3:
      System.println("three");
      x++;
      continue;
    case 4:
      System.println("four");
      x++;
      continue;
  }
}

Given that "continue" restarts a switch statement, then calling foo(1), you might expect to get "one, two, three, four" printed out. But in fact, it just prints "one,one,one,one" until the watchdog timer kills the app.

So the bug report is that:

  • The behavior of continue in a switch isn't documented (at least, I couldn't find any documentation)
  • The currently implemented behavior is confusing, and not useful. Having it restart the switch could be useful, but (as far as I can see) only if it re-evaluates the switch condition. As implemented, "continue" simply goes back to the same case that was originally chosen, even though the switch condition might have changed.

Finally, while searching for documentation about this, I came across this (completely unrelated) example on https://developer.garmin.com/connect-iq/reference-guides/monkey-c-reference/

switch (myValue) {
    case true:
        // Variable 'a' is scoped at the switch block level
        var a = 1;
    case 1:
        // Results in a compiler error because 'a' was not initialized in this case block
        var z = a;
        break;
    case "B": {
        // Variable 'a' is scoped at the code block level within the curly braces, so no scoping
        // conflict with 'a' at the switch block level
        var a = true;
        break;
    }
    case instanceof MyClass:
        // Results in a compiler error because 'a' has already been defined in the switch block
        var a = "Hello!"
    default:
        // No errors because 'a' was defined in the first case and initialized at the beginning of
        // the default case
        a = 0;
        var b = a;
}

The comments for case "B" are wrong. "var a;" is now an error (I believe it was ok prior to sdk-4.x). You can no longer have two local variables with the same name live at the same point in the program, regardless of scoping.

Parents Comment Children
No Data