Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unsigned int reverse iteration with for loops

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.

like image 418
deceleratedcaviar Avatar asked Mar 28 '11 11:03

deceleratedcaviar


People also ask

Can you use unsigned int in for loop?

Do not use `unsigned int` as loop variable in C++ code exercises · Issue #693 · udacity/sdc-issue-reports · GitHub.

Can a function return unsigned int?

Unsigned int can also be declared in the function argument.

How do you reverse a loop in C++?

In C#, using Visual Studio 2005 or later, type 'forr' and hit [TAB] [TAB]. This will expand to a for loop that goes backwards through a collection. It's so easy to get wrong (at least for me), that I thought putting this snippet in would be a good idea.

What is unsigned int c?

An unsigned Integer means the variable can hold only a positive value.


1 Answers

You can use

for( unsigned int j = n; j-- > 0; ) { /*...*/ } 

It iterates from n-1 down to 0.

like image 157
Serge Dundich Avatar answered Oct 21 '22 22:10

Serge Dundich