extern(C) enum

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Sep 16 02:01:56 UTC 2017


On Friday, September 15, 2017 19:04:56 jmh530 via Digitalmars-d-learn wrote:
> On Friday, 15 September 2017 at 18:20:06 UTC, Jonathan M Davis
>
> wrote:
> > It is my understanding that for both C and C++, an enum is
> > always an int (unless you're talking about enum classes in
> > C++). The size of an int can change based on your architecture,
> > but AFAIK, all of the architectures supported by D guarantee it
> > it be 32 bits in C/C++ (certainly, all of the architectures
> > supported by dmd do), and druntime would have serious issues if
> > it were otherwise, as it assumes all of the place that D's int
> > is the same as C/C++'s int.
> >
> > It's certainly possible that my understanding of C/C++ enums is
> > wrong, but if it is, you'd basically be screwed when dealing
> > with any C functions that take an enum in any case that an enum
> > wasn't 32 bits - especially if the C/C++ compiler could choose
> > whatever size it wanted that fit the values.
> >
> > - Jonathan M Davis
>
> Not to hijack the thread, but is there anything about enums that
> can't be done with a struct? The code below is just a simple
> example that I'm sure I could complicate unnecessarily to
> re-create much of the behavior of current enums with the syntax
> of std.tuple.
>
> I suppose what I'm wondering how E.B below is treated in the
> writeln. With an enum, it would be a manifest constant. Does
> static initialization of the struct do the same thing?
>
> struct Enum(T)
> {
>      T A;
>      T B;
> }
>
> static Enum!int E = {A:0, B:1};
>
> void main()
> {
>      import std.stdio : writeln;
>
>      writeln(E.B);
> }

If you do that instead of using enum, you completely lose the extra bit of
type safety that enums give you (e.g. assigning a string to a variable whose
type is an enum that's a base type of string is not legal) - though the type
system is still annoyingly liberal with what it allows for enums (e.g.
appending to an enum of base type string is legal, and doing bitwise
operations on an enum results in the enum type instead of the base integral
type). And final switch wouldn't work with the struct, whereas it does with
enums. Also, a number of things in the standard library specifically treat
enums in a special way (e.g to!string and writeln use the enum's name rather
than it's value), and that would not happen with your struct. With your
struct, you've just namespaced a group of constants. Other than that,
they're the same as if they were declared outside of the struct, and while
IMHO D's enums are annoyingly lax in some of what they allow, they do do
more with the type system than a manifest constant would.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list