On 02/25/2011 10:52 AM, Andrej Mitrovic wrote:
So I'd like to print all values storable in a byte in hex representation:

import std.stdio;
void main()
{
     int counter;
     foreach (byte index; byte.min..byte.max)
     {
         if (!(counter % 4))
             writeln();

         writef("%#.2x, ", index);
         counter++;
     }
}

If you run this, you'll realize that it doesn't print the final 0x7F. This is 
because in a foreach range literal (is that the correct term?), the left side 
is inclusive, but the right side isn't.

I've seen the same "problem" with enums.

import std.stdio;

enum E { x, y, z }

void main()
{
    foreach (e; E.min .. E.max) {
        writeln(e);
    }
}

The value 2 is excluded. Of course it's rare to use enums like that in a foreach loop as their values are not always continuous.

I found out the better solution before sending this message:

    foreach (e; __traits(allMembers, E)) {
        writeln(e);
    }

The difference is, the type of 'e' is string above. Finally, the following produces integer values:

    foreach (e; __traits(allMembers, E)) {
        writeln(to!E(e));
    }

Ok, good... :)

Ali

Reply via email to