www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Unions and array length...

  In the array structure, either the length is how many elements 
of that type there are, or how many bytes total the array takes 
up. This can create a slight problem if used in a union (or so 
I've found).

Currently this is how it works:

   union {
     ubyte[] ub;
     int[] i;

   i = new int[8];
   assert(i.length == 8);

  Since ints are 4 bytes...
   i[0 .. 8] = 84;   //works as expected
   ub[0 .. 32] = 42; //range violation!

  If you write them with writeln you get a very specific picture.

   writeln(int.length); //8 as expected
   writeln(ub.length);  //8, NOT 32

  You've have to cast it to fix the length (but you can't recast 
over and over in a union). If it had the number of bytes, it 
would have a slight overhead (maybe 1 instruction at best as a 
shift operator in most cases) to translate it.

  If it was the number of bytes instead...

   i = new int[8]; //32 bytes

   assert(i.length == 8);
   assert(ub.length == 32);

   i[0 .. 8] = 84;   //works as expected
   ub[0 .. 32] = 42; //range/length within byte size, so is okay

  Now other than getting the length slightly faster, is there any 
important reason why it's by how many and not how big the area 
Aug 14 2012