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 by clugdbug — 2009-04-08T02:08:31Z
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 by clugdbug — 2009-04-08T02:09:52Z
*** Bug 2792 has been marked as a duplicate of this bug. ***
Comment #3 by clugdbug — 2009-04-08T02:20:18Z
Possible the same as bug 1884.
Comment #4 by clugdbug — 2010-10-19T23:54:24Z
This was fixed in DMD2.031. The reduced test case was wrong! Should have been int x=2;