Wrong enum comparisons

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Mon May 28 06:47:42 PDT 2012


On 5/28/12 8:19 AM, foobar wrote:
> I have to loudly object to this definition. Given a typical enumeration
> such as:
> enum color {Blue, Green, Red};
> Who's to say that Blue must equal 0? This is conceptually plain *wrong*.
>
> A conceptually correct enumeration must NOT expose such implementation
> details as the very poor C/D style enums do.

Depends on what the concept is. The archetype for "enumerating" is 
natural numbers, and in that view there's nothing wrong to attach a 
natural ordinal to each element of an enumeration.

I do agree that it's wrong to _conflate_ the enumerated value with it 
ordinal, so in this program neither comparison should compile without an 
explicit cast:

enum E1 { A, B }
enum E2 { C, D }

void main() {
     E1 a;
     assert(a == 0);
     assert(a == E2.C);
}

The first one is probably difficult to disallow at this time, but the 
second one almost always indicates a bug, confusion, or abuse on the 
user side. We should disallow it.

> See functional languages
> such as ML for a correct implementation and also Java 5 Enums (similar
> but with an OO flavor).

I've always found it amusing to watch what a kitchen sink Java 
enumerations have become. It's as if someone said, "so you complain Java 
doesn't have enum? I'll give you enum!" I think we shouldn't copy that 
design.


Andrei


More information about the Digitalmars-d mailing list