-------------------------------
union TwoInts
{
struct
{
int _0;
int _1;
}
int[2] array;
}
private int sum()
{
auto twoValues = TwoInts();
twoValues._0 = 100;
twoValues._1 = 200;
int x;
foreach(i; 0..2)
{
x += twoValues.array[i];
}
return x;
}
//enum v = sum(); // ERROR
void main()
{
import core.stdc.stdio;
printf("sum is %d\n", sum());
}
-------------------------------
If you uncomment the `enum v = sum();` AND comment out the print line you'll get this error:
bug.d(18): Error: `twoValues.array[cast(uint)i]` is used before initialized
bug.d(6): originally uninitialized here
bug.d(23): called from here: `sum()`
Comment #1 by simen.kjaras — 2018-06-01T09:01:55Z
Unions generally don't work in CTFE. This issue is actually just a case of a wrong error message - the correct error message is 'Error: reinterpretation through overlapped field array is not allowed in CTFE', as can be seen in this code:
union U
{
int a;
int b;
}
int fn()
{
U u;
u.a = 3;
return u.b;
}
enum v = fn();
Comment #2 by robert.schadek — 2024-12-13T18:58:58Z