For a class I'm teaching I needed to write a piece of code to iterate over all possible char values. I wanted to do this in a way that was portable across different C++ implementations. This meant that
- I can't assume
charissignedorunsigned, - I can't assume
charis eight bits, - I can't assume that
sizeof(int) > 1, - I can't assume the
int32_tetc. types exist, - I can't assume that integer overflow will not trap,
- etc.
The best solution I came up with was the following unusual do ... while loop:
char ch = numeric_limits<char>::min();
process(ch);
do {
ch++;
process(ch);
} while (ch != numeric_limits<char>::max());
This approach works, but it feels pretty clunky to me. It intuitively makes sense that an approach like this might be needed because the number of increments is one more than the number of possible characters, but perhaps there's a fundamentally different approach available that more closely resembles a traditional for loop.
Is there a portable way to achieve this that's less clunky than this?