181
Ideas / Re: Switch statement
« on: October 26, 2018, 11:34:34 PM »
Let me go a bit further:
There is no real reason why switch can't have more extended functionality:
1. Allow "case" to be followed by any expression
2. Allow switch to be without value
3. Compile "expression"-case to nested ifs, and regular values to normal switch/case.
E.g.
To simplify, type (2) can be eliminated entirely. That also makes it clearer when we have possible jump tables and when not.
Compare case (1) with if/else:
However, the "break" statement makes is a little less useful. In languages where "fallthrough" is required, this can be shortened further:
A "break"-less switch would also allow for automatic scopes with each case. But that idea has to be refined a bit.
Anyway, just posting this as food for thought.
There is no real reason why switch can't have more extended functionality:
1. Allow "case" to be followed by any expression
2. Allow switch to be without value
3. Compile "expression"-case to nested ifs, and regular values to normal switch/case.
E.g.
Code: [Select]
// (1) Compiles to if/else
switch
{
case (x > 0): do_something(); break;
case (y < 10): do_something_else(); break;
case (x + y < 1): foo(); break;
}
// (2) Compiles to if/else
switch (x)
{
case 0: zero_handle(); break;
case x > 0: do_something(); break;
case y < 10: do_something_else(); break;
case x + y < 1: foo(); break;
}
// (3) This compiles to switch/case
switch (x)
{
case 0: ... break;
case 1: ... break;
default: ... break;
}
To simplify, type (2) can be eliminated entirely. That also makes it clearer when we have possible jump tables and when not.
Compare case (1) with if/else:
Code: [Select]
switch
{
case (x > 0):
do_something();
break;
case (y < 10):
do_something_else();
break;
case (x + y < 1):
foo();
break;
}
if (x > 0) {
do_something();
} else if (y < 10) {
do_something_else();
} else of (x + y < 1) {
foo();
}
However, the "break" statement makes is a little less useful. In languages where "fallthrough" is required, this can be shortened further:
Code: [Select]
switch
{
case (x > 0):
do_something();
case (y < 10):
do_something_else();
case (x + y < 1):
foo();
}
A "break"-less switch would also allow for automatic scopes with each case. But that idea has to be refined a bit.
Anyway, just posting this as food for thought.