Iterating over the full range of an integer type

c++, iteration

Solution

For an unsigned integral type,

unsigned x = 0;
do {
    // something with x
} while (++x > 0);

You can do this because unsigned integral types obey the laws of arithmetic modulo 2^n.

For a signed integral type, something like this would work, though it's a bit less clean:

int x = std::numeric_limits<int>::min();
while (true) {
    // do something with x
    if (x == std::numeric_limits<int>::max()) break;
    x++;
}

Problem

My first question is, what is the best way to iterate over the entire range of possible values for a particular type? There seems to be no really clean way to accomplish this.

Original source