www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Enums - no "out of range" checking?

reply Tommy <Tommy_member pathlink.com> writes:
/*
Compiles and works fine (output: 15), although I think it shouldn't.
*/

import std.c.stdio;

enum X { A, B, C }
// Define a new type X which has values X.A=0, X.B=1, X.C=2

void foo(X bar)
{
printf("%d\n", bar);
}

void main()
{
foo(15);
/* Named enum members can be implicitly cast to integral types,
but integral types cannot be implicitly cast to an enum type. (From the official
D docs)
Shouldn't the D compiler catch this error? 15 is clearly out of range with
regards to
the type X. */
}
Oct 01 2005
next sibling parent reply AJG <AJG_member pathlink.com> writes:
In article <dhn382$1lk5$1 digitaldaemon.com>, Tommy says...
/*
Compiles and works fine (output: 15), although I think it shouldn't.
*/

import std.c.stdio;

enum X { A, B, C }
// Define a new type X which has values X.A=0, X.B=1, X.C=2

void foo(X bar)
{
printf("%d\n", bar);
}

void main()
{
foo(15);
/* Named enum members can be implicitly cast to integral types,
but integral types cannot be implicitly cast to an enum type. (From the official
D docs)
Shouldn't the D compiler catch this error? 15 is clearly out of range with
regards to
the type X. */
}
Indeed. Currently, enum handling in D is kinda poor. It's basically a fancy #define. IMHO, of course. Cheers, --AJG.
Oct 01 2005
parent Tommy <Tommy_member pathlink.com> writes:
In article <dhn4qs$1n7p$1 digitaldaemon.com>, AJG says...

Indeed. Currently, enum handling in D is kinda poor. It's basically a fancy
#define.
OK. Thanks, anyway... :-) Tommy
Oct 03 2005
prev sibling parent Sean Kelly <sean f4.ca> writes:
In article <dhn382$1lk5$1 digitaldaemon.com>, Tommy says...
/*
Compiles and works fine (output: 15), although I think it shouldn't.
*/

import std.c.stdio;

enum X { A, B, C }
// Define a new type X which has values X.A=0, X.B=1, X.C=2

void foo(X bar)
{
printf("%d\n", bar);
}

void main()
{
foo(15);
/* Named enum members can be implicitly cast to integral types,
but integral types cannot be implicitly cast to an enum type. (From the official
D docs)
Shouldn't the D compiler catch this error? 15 is clearly out of range with
regards to
the type X. */
}
enums are also treated as integers when used as template parameters. I haven't yet decided if this is a good thing or not. Sean
Oct 01 2005