Bug 4261 – Bad textual printing of enums

Status
RESOLVED
Resolution
FIXED
Severity
normal
Priority
P2
Component
phobos
Product
D
Version
D2
Platform
x86
OS
Windows
Creation time
2010-06-02T14:47:00Z
Last change time
2015-06-09T05:14:47Z
Assigned to
nobody
Creator
bearophile_hugs

Comments

Comment #0 by bearophile_hugs — 2010-06-02T14:47:27Z
This D2 program: import std.stdio: writeln; void main() { enum Foo { Zero, One } Foo f = Foo.One; writeln(f); } With DMD v2.046 prints: 1 But it's better for it to print: One See also bug 3308.
Comment #1 by andrej.mitrovich — 2010-08-29T21:16:37Z
When you need to get the name of the enumerated value, you have to use the 'to' template function from std.conv, as described in TDPL. Your example then becomes: import std.conv : to; import std.stdio: writeln; void main() { enum Foo { Zero, One } Foo f = Foo.One; writeln(to!string(f)); } Prints: One It wouldn't make much sense for an enum to behave differently in different contexts (e.g. comparing it in an if statement vs. using it with a writeln).
Comment #2 by bearophile_hugs — 2010-08-30T04:37:55Z
Enums aren't numbers, they are symbols that the language/CPU often represents with numbers. See also bug 3999
Comment #3 by andrej.mitrovich — 2010-08-30T05:47:34Z
I'm not sure I understand what you're saying. An enum in D is a list of symbolic values of any type (except classes). For example: module enums; import std.stdio; struct Color { ubyte r, g, b; } enum { red = Color(255, 0, 0), green = Color(0, 255, 0), blue = Color(0, 0, 255) } void foo(Color c) { writefln("%s %s %s", c.r, c.g, c.b); } void main() { foo(blue); } enums are also used in CTFE, e.g.: enum float value = someFunc(); // CTFE Having to use a cast everywhere for an enum would break a lot of code.
Comment #4 by bearophile_hugs — 2010-08-31T18:57:48Z
What I am saying in bug 3999 is relative to just the case where the enum has a EnumTag. In this case I prefer the enum to be like a typedef (as the C++0x "enum class") and require a cast if you want to use/compare it as/to the base type. In your example red, green and blue are inside an anonymous enum (it lacks a EnumTag), so in this case the cast is not necessary. So that code is not affected.
Comment #5 by kennytm — 2011-06-02T11:13:54Z