16
Ideas / Switch proposal
« on: November 28, 2018, 12:27:25 PM »
Putting it here instead as a comment in a longer discussion
Here is the propsal:
Another possibility is |: or :|
Using | means a that some care must be taken if there is an expression of type:
case 1|2: (This is is compiled to case 3: or course, but I think it's reasonable to require ( ) on any constant expression that isn't a literal.
So case 1+2: would not be allowed, but case (1+2): is ok.
Alternatives to goto next would be:
An even more lightweight syntax uses | for fallthrough, leading to this uniform syntax look:
Here is the propsal:
Code: [Select]
switch (a) {
case 1 | // Using : instead of | is syntax sugar for case 1: goto next;
case 2 |
case 3:
foo(); // With : we get a break;
case 4 |
case 5:
bar();
goto next; // If we want to execute a statement then pass to next.
case 6:
baz();
}
// The above in C:
switch (a) {
case 1:
case 2:
case 3:
foo();
break;
case 4:
case 5:
bar();
case 6:
baz();
break;
}
Another possibility is |: or :|
Code: [Select]
switch (foo) {
case 1|:
case 2|:
case 3:
do_something();
Using | means a that some care must be taken if there is an expression of type:
case 1|2: (This is is compiled to case 3: or course, but I think it's reasonable to require ( ) on any constant expression that isn't a literal.
So case 1+2: would not be allowed, but case (1+2): is ok.
Alternatives to goto next would be:
Code: [Select]
case 4:
foo();
fallthrough;
case 5:
...
case 4:
foo();
goto case 5;
case 5:
...
case 4:
foo();
goto case;
case 5:
...
case 4:
foo();
continue case;
case 5:
...
case 4:
foo();
next;
case 5:
...
case 4:
foo();
next case;
case 5:
...
case 4:
foo();
nextcase;
case 5:
...
An even more lightweight syntax uses | for fallthrough, leading to this uniform syntax look:
Code: [Select]
case 4:
foo();
| case 5:
...
Code: [Select]
switch (a) {
case 1:
| case 2:
| case 3:
foo(); // implicit break here
case 4 :
| case 5:
bar(); // Fallthrough here because the next starts with |
| case 6:
baz();
}