for(int i(5) ; i-->0 ; ) { //use i as iterator here }
Is this the same as
for(int i=5; i>0 ; i--) ??
I tried to find similar declarations in google but didn't find anything
Also please suggest cleaner ways to declare the same thing ?
No these aren't the same. In the first case, i will be decremented before the loop body is executed for the first time.
See http://ideone.com/AbHF3m for a working demo.
i is 4 when the loop body executes. Unlike the other version, where it's 5 the first time it executes.No, it's not the same. The first version compares the value of i before the decrement, and performs the decrement before each iteration; the second compares the value after the decrement, and performs the decrement after each iteration.
So the first iterates over {4,3,2,1,0}, while the second iterates over {5,4,3,2,1}.
i>0 in that version has no effect, but otherwise yes; i-- will give the same boolean result as i-->0 if i starts out non-negative.i before the decrement (i.e. compares 5>0), and performs the decrement before each iteration (i.e. decrements to 4 for the first iteration).It's not the same. In the first case, the value of i will be 4 in the first iteration and 0 in the last one. In the second case, i will be 5 in the first iteration and 1 in the last one.
Edit
For @Y.Ecarri:
First case:
i to 5i > 0, that is, 5 > 0i. i is now 4i having value 4Second case:
i to 5i > 0, that is, 5 > 0i having value 5i. i is now 4They are not the same as others have pointed out as order is:
If i is a signed int as here so it can reach -1, you can replace with
for( int i=4; i >= 0; --i ) { // body which looks a bit more obvious in its intention. If you have an unsigned int e.g. size_t, you can still make it look a bit more obvious in its intent by switching the order
for( size_t i = 5; 0 < i--; ) { // body You can also remove the 0 and the comparison altogether and just do
for( size_t i = 5; i--; ) { // body In both of the above two I am still uncomfortable with the fact that you start i=5 when you really want it to start as 4 for the first iteration. So I might even switch to do...while.. Of course I have to initialise i outside the loop.
size_t i = 5; do { // body --i; // clearly 4 now on first iteration } while( i != 0 ); i is different between the first and the last two examples. I will be decremented before the execution of the loops body while in the first example it gets decremented after the body. Have a look at Mike Seymours answer. Maybe you should highlight this with //body i =4 in your example.
for(int i=4; i>=0 ; i--)