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
I would use two variables:
unsigned int start = 10;
for (unsigned int j = 0, i = start; j <= start; ++ j, -- i) {
// ...
}
You can also use a while loop:
unsigned int start = 10;
unsigned int i = start + 1;
while (i --) {
// ...
}
One more way:
for(unsigned i = n-1; i < n ; --i)
{
// Iterates from n-1 to 0
}
Simillarly for size_t (unsigned integer type) use the same trick
for(std::size_t i = n-1; i < n ; --i)
{
// Iterates from n-1 to 0
}
You can use
for( unsigned int j = n; j-- > 0; ) { /*...*/ }
It iterates from n-1
down to 0
.
Just:
int start = 10;
for(unsigned int iPlus1 = start + 1 ; iPlus1 > 0 ; iPlus1--) {
// use iPlus1 - 1 if you need (say) an array index
a[iPlus1 - 1] = 123; // ...
}
No?
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 ?
The following does what you want:
for (unsigned i = 10; i != static_cast<unsigned>(-1); --i)
{
// ...
}
This is perfectly defined and actually works. Arithmetic on signed types is accurately defined by the standard. Indeed:
From 4.7/2 (regarding casting to an unsigned type):
If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2^n where n is the number of bits used to represent the unsigned type)
and 3.9.1/4
Unsigned integers, declared unsigned, shall obey the laws of arithmetic modulo 2^n where n is the number of bits in the value representation of that particular size of integer