Alex Rivera | Logout

Unsigned int reverse iteration with for loops

Asked 2011-03-28T11:18:37.203
56

I want the iterator variable in a for loop to reverse iterate to 0 as an unsigned int, and I cannot think of a similar comparison to i > -1, as you would do if it was a signed int.

for (unsigned int i = 10; i <= 10; --i) { ... }

But this seems very unclear, as it is relying on the numerical overflow of the unsigned integer to be above 10.

Maybe I just don't have a clear head, but whats a better way to do this...

Disclaimer: this is just a simple use case, the upper limit of 10 is trivial, it could be anything, and i must be an unsigned int.

Edit
Report

2 Answers

3

Are you really iterating down from some number greater than std::numeric_limits<int>::max()? If not, I would actually suggest just using a normal int as your loop variable and static_cast it to unsigned in the places in your code that expect it to be unsigned. This way you can use the intuitive >= 0 or > -1 condition and in general I would expect it to be more readable than any of the unsigned alternatives.

The static_cast would just be to tell the compiler how to operate on the variable and have no performance implications at all.

answered 2011-03-28T13:31:46.760
0
for(unsigned i = x ; i != 0 ; i--){ ...

And if you want to execute the loop body when i == 0 and stop after that. Just start with i = x+1;

BTW, why i must be unsigned ?

answered 2011-03-28T11:29:04.447

Your Answer