Weird while loop

okay maybe not so weird...

1
2
3
4
while (i--)
{
//some code goes here...
}

I have never seen a while loop that takes i-- as a condition. What does this mean in terms of the while loop?

Thanks so much.
Last edited on
Ugh... what an ugly loop conditon.


The condition of a while loop evaluates to either true (if nonzero) or false (if zero). So while(6) is the same as while(true)... and while(i) is the same as while(i != 0).

That said... i-- evaluates to the OLD value of i (prior to decrementing). Therefore:

1
2
3
4
5
6
int j = i--;

// is the same as:

int j = i;
i--;



So the loop basically decrements i before each iteration, and the loop stops when i drops below zero (because the old value of i would've been zero).

It's confusing, yes. This is an ugly loop.

It'd work out like this:

1
2
3
4
5
6
int i = 5;
while(i--)
{
  cout << i;  // 43210
}
cout << i; // -1 
Last edited on
The way you described it is actually not that confusing.

Thank you.
well it wont work i think...
cause i know about loops is this...


while ( condition ){
//here lies the operations such as 'x = y' and etc. and as well as the
//updater like 'x += 1' , x++, x-- and so on.
}

for ( initiator; condition; updater ){
//operations
}
//initiator is like the initializer it set value of the updater and condition or what so ever needed in //the for loop

do {
//operations
//updater
} while ( conditions);

jah get it?
Well waddaya know... god isn't omniscient after all.

condition is any expression that can be converted to bool. C, and therefore C++, allows
implicit conversion from int to bool, and guarantees that the integer value zero equates
to false, and all other integer values equate to true.
wow... god was amazed!!!!
Topic archived. No new replies allowed.