D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 2559 - bad code generation for enum arrays
Summary: bad code generation for enum arrays
Status: RESOLVED FIXED
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: x86 Windows
: P1 critical
Assignee: No Owner
URL:
Keywords: accepts-invalid, wrong-code
: 2792 (view as issue list)
Depends on:
Blocks:
 
Reported: 2009-01-06 12:59 UTC by Koroskin Denis
Modified: 2015-06-09 01:20 UTC (History)
2 users (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description Koroskin Denis 2009-01-06 12:59:45 UTC
void foo(int offset)
{
    enum i1 = [1, 2, 3];
    invariant(int[]) i2 = [1, 2, 3];


    writefln(i1[offset]); // prints garbage
    writefln(i2[offset]); // prints valid value
}

foo(0);

Test run result:
-------
4315632
1
Comment 1 Don 2009-04-08 02:08:31 UTC
I've changed the title, since I believe this bug is extremely serious.
Simpler example:
--------------
enum ubyte[4] a = [5,6,7,8];

void main()
{
  int x=3;
  assert(a[x]==7);
}
-----------
Interestingly, compiling with -O gives
bug.d(7): Error: variable a used before set

which shows that the initializer is being ignored.
My opinion is that that's correct -- the only reason you're using an enum is so that it doesn't appear in the executable! Using a variable to index into the enum is arguably equivalent to taking the address of the enum, and should therefore be illegal -- use "immutable" instead.
Comment 2 Don 2009-04-08 02:09:52 UTC
*** Bug 2792 has been marked as a duplicate of this bug. ***
Comment 3 Don 2009-04-08 02:20:18 UTC
Possible the same as bug 1884.
Comment 4 Don 2010-10-19 23:54:24 UTC
This was fixed in DMD2.031. The reduced test case was wrong! Should have been int x=2;