You almost wonder if they could do something like how `enum` got fixed up with proper scoping as `enum class`. Like, could `switch` retain the legacy functionality with the new stuff triggered when you do `switch from`, `switch if`, or similar. Or there could be new keyword added after the parenthesis, something like:
switch(<thing>) cases {
<opt1> : ...;
<opt2> : ...;
__ : ...;
}
This has a clear connection back to the legacy command in terms of a switch always having either case labels or a cases structure. And zero chance of breaking existing code, given that the `cases` keyword would only be valid in that position and could still be used as an identifier elsewhere (though obviously that would be discouraged).As for efficiency, we have decades of experience of compiling pattern matching, so i would be surprised if it was always just an if-else ladder. The authors of the proposal to add it to Java think that, compared to explicit if-elses, "it is more optimizable too; in this case we are more likely to be able to do the dispatch in O(1) time":
https://openjdk.java.net/jeps/8213076
I imagine this is through approaches which convert the cases to integers, and then do a traditional jump table etc.
If there's a real inspect, people will be able to stop treating switch as a deficient approximation to one, and maybe appreciate it for what it is.
However, this means switch _only_ works with integers, which is rather limited and confuses newcomers. For instance this does not compile:
void f(std::string const &str) {
switch(str) {
case "option_1":
std::cout << "First option\n";
break;
case "option_2":
std::cout << "Second option\n";
break;
default:
std::cout << "None of the above\n";
}
} void f(std::string const &str) {
switch(hash(str)) {
case hash("option_1"):
std::cout << "First option\n";
break;
case hash("option_2"):
std::cout << "Second option\n";
break;
default:
std::cout << "None of the above\n";
}
}
It could be as little as converting the final 8 bytes to a uint64_t above and using that. That just happens to be all of them in this case, but there are a bunch of them. Or using minimal perfect hashing. None of this is the language though[1] https://github.com/dvx/lofi/blob/master/src/renderer/compone...
Here's a poor-man's coroutine (with serializable state!) where switch plays a more interesting role.
void move_robot(state* s) {
switch (s->resume_at) {
case 0:
#define SUSPEND(resume_pt) s->resume_at = resume_pt; return; case resume_pt:;
#define PAUSE(resume_pt) s->pause_time = 20; while (s->pause_time) { SUSPEND(resume_pt) }
for (;;) {
/* three knight moves, then forward */
for (s->i = 0; s->i != 3; s->i++) {
forward(s);
PAUSE(1);
forward(s);
PAUSE(2);
turn_left(s);
forward(s);
PAUSE(3);
}
forward(s);
}
}
}