Search code examples
d

D: Templated structure : not initializing


I am trying to learn D (Googling for this language is impossible, btw. tips on that?), and am stuck with this problem.

Consider:

// Bitfield utilities
struct RegBit(int bitnumber, int nbits, T) {
    T data;
    uint mask = 46;
    ubyte r = 3;
}

struct cpu_t {

// registers
union {
    ushort AF = 56;
    struct {
        ubyte F;
        ubyte A;
    };
    // flags
    RegBit!(7, 1, ushort) fZ;
    RegBit!(6, 1, ushort) fN;
    RegBit!(5, 1, ushort) fH;
    RegBit!(4, 1, ushort) fC;
};

then running this,

writefln ("%d", CPU.fC.data);
writefln ("%d", CPU.fC.r);

begets the output

56
0

my question is: why?


Solution

  • the only field of the union that gets initialized is AF and this happens to coincide with the data field of the RegBit structs. All the rest just gets ignored during standard initialization so the r fields of the RegBits never get touched (and would all be the same anyway)

    the true issue is the use of the union, honestly you shouldn't need it in most cases