removing default case requirement?

Salih Dincer salihdb at hotmail.com
Sat Apr 15 00:39:07 UTC 2023


On Tuesday, 4 April 2023 at 12:47:18 UTC, Quirin Schroll wrote:
> I don’t really care. In my experience, a switch is one of the 
> two cases: Every case leads to a return or every case leads to 
> a break. Occasionally, there are cases ending in throw. When I 
> code C#, which I do occasionally, I almost never use switch 
> statements, but switch
> expressions¹, where every code path necessarily must return a 
> value. The best part about C#’s switch expressions is that they 
> don’t need (or even allow for) break. I consider switch 
> statements like goto: It’s there when you need it, but it 
> shouldn’t be your first attempt.

Although I like the switch, the use of a look-up table increases 
the assembly code when operating within a certain range (chain of 
possibilities). For example, the first code snippet is more 
efficient:

```d
import core.stdc.stdio: printf;

void main() {
  char letter = 63;
  while(++letter) {
    //* <- remove slash for toggle-snippet2 on:
    if(letter > 64 && letter < 91) {
      printf("capital: %c\n", letter);
    } else if(letter > 96 && letter < 123) {
      printf("small: %c\n", letter);
    }/*/
   switch(letter) {
     case 'A': .. case 'Z':
       printf("capital: %c\n", letter);
       break;
     case 'a': .. case 'z':
       printf("small: %c\n", letter);
       break;
     default:
    }//*/
  }
}
```
I also like the second snippet, but it is necessary to use it 
carefully. Even if you compile with -O2, a rodata segment 
(.rodata) is generated unnecessarily.

https://d.godbolt.org/z/1q5YoPosT

Going back to our topic, don't take away the default! Because we 
need it in this example.

SDB at 79


More information about the Digitalmars-d mailing list