Enum literals, good? bad? what do you think?

Patrick Schluter Patrick.Schluter at bbox.fr
Thu Jul 22 07:42:33 UTC 2021


On Thursday, 22 July 2021 at 04:37:43 UTC, Walter Bright wrote:
> On 7/21/2021 8:47 PM, Mathias LANG wrote:
>> What I meant was that instead of recommending our users to use 
>> `switch (value) with `(EnumType)`, we could just make it the 
>> default since it's the common case with enums. Unless we think 
>> that requiring the type of the enum be spelt out is better.
>> 
>> It could add to the long list of those usability enhancements 
>> that are a hallmark of D (like `_` in number literals). I 
>> personally don't mind the verbosity, but I heard this 
>> complaint a few times over the years.
>
> Ok, I see what you mean. If it was restricted to the case value 
> expressions, there is merit to the idea. But suppose:
>
>     enum A = 3, B = 4;
>     switch (x) {
>       case A: ...
>       case B: ...
>     }
>
> there isn't much of a clue that `case A` is not `case 3`, which 
> matters more and more the larger the program gets.
Currently, that's what happens

     ```
     	enum ENUM { A, B, C }
         ENUM x = ENUM.A;
         enum A = 3, B = 4;

         switch (x) /*with (ENUM)*/ {
            case A: writeln("case A=", cast(int)A);break;
            case B: writeln("case B=", cast(int)B);break;
            default:writeln("whatever x=", cast(int)x);
         }
     ```
     onlineapp.d(11): Error: cannot implicitly convert expression 
`3` of type `int` to `ENUM`
     onlineapp.d(12): Error: cannot implicitly convert expression 
`4` of type `int` to `ENUM`
     onlineapp.d(12): Error: duplicate `case 4` in `switch` 
statement

https://run.dlang.io/is/a12yVL

The compiler will already do the right thing as it cannot convert 
the `enum A` and `enum B` to the type of x.

>
> One thing I've learned with D is that programmers often have 
> mental models of how symbol lookup is done that diverge 
> substantially from how it actually works, and I've never been 
> able to communicate how things actually work to them. Putting a 
> special case in like this is pretty risky.




More information about the Digitalmars-d mailing list