Type checking on typed enum

Jonathan M Davis jmdavisProg at gmx.com
Sun Sep 16 16:40:09 PDT 2012


On Monday, September 17, 2012 01:03:46 ixid wrote:
> If I use code like:
> 
> enum ulong VAR = 10;
> 
> I'd have expected this to be type checked when used as a ulong.
> Instead it seems to be checked based on its absolute value and is
> accepted for a function like:
> 
> void fun(int n) {
>      // Do stuff
> }
> 
> If the value of VAR is set to more than int.max then the compiler
> (DMD2 latest non-beta) notices the type mismatch. This would seem
> like an understandable enum behaviour if VAR was just enum rather
> than enum ulong but intuitively I'd have expected the specifier
> to limit what would accept the enum. Is this how it's supposed to
> work? As a beginner with D I came across the advice that enum was
> the correct way to specify global constants but this makes it
> feel safer to use const when you want type checking and perhaps
> enum isn't the right choice.

That's how it works with integral values in general in D. If the compiler can 
determine that the integral value will fit in the type that you're trying to 
assign it to, then it'll let you do it. There's a term for this, but I forget 
what it is at the moment. It's a very deliberate feature decision which does 
vary from how it works in C/C++, and it shouldn't cause you any problems.

In most cases, of course, the compiler has no idea what the value of your 
variable is and will have to assume that it's larger than will fit if a 
narrowing conversion is required, but with an enum, it always knows what the 
value is. But I'd expect that you'd get the same behavior if you changed VAR 
to immutable or const, because it's value would still always be known.

Now, if you overloaded fun on int and ulong, then the ulong version should be 
used, because you typed VAR as being ulong, but as long as there's no 
ambiguity, and the compiler knows that the value that you're trying to assign 
to a smaller integral type will fit in that smaller integral type, it should do 
the narrowing conversion without an explicit cast.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list