Why the loop stops when i = -1?
for (i = len; i--;)
Full code is here http://rosettacode.org/wiki/Longest_increasing_subsequence#C .
Thx!!
Why the loop stops when i = -1?
for (i = len; i--;)
Full code is here http://rosettacode.org/wiki/Longest_increasing_subsequence#C .
Thx!!
The loop stops when the value of i--
is 0
. Since i--
returns the value before the decrement, when i--
is 0
, i
is -1
.
I don't see an answer worthy of being right, though Joachim Isaksson's comment is a concise explanation.
The loop stops when it evaluates a value of 0 or false.
The i--
is what's throwing you off. That's "post-decrement", i.e. the operator returns the current value of i (in this case, for the loop to evaluate), and immediately thereafter, decrements the current value. Pseudocode for postdecrement follows:
int retval = i;
i = i - 1;
return retval;
(Based on Eric Lippert's comments, technically, the compiler could do postdecrement as i = i - 1; return i + 1;
. The point is that the value emitted by the operator is no longer the value of i
.)
(as opposed to predecrement, which in pseudocode is simply):
i = i - 1;
return i;
So when the loop is evaluating i
, it sees 0 so exits, but immediately after evaluating the operator has decremented i
to -1.
So, to answer your question:
The loop doesn't stop when i = -1. It stops when i = 0, but then i is decremented to -1.
Your loop stops when the expression i--
becomes 0
because any non-zero value in C is treated as true
and a zero as false
.
At each iteration i
is checked for true
or false
and then decremented .
for (i = len; i--;)
here i-- is the exit condition. when i-- is false which is 0 the loop will exit.
since i-- is post decreament i
value is used for condition checking. so when
i=0;
loop exits after that i=i-1
is executed as part of post decrement so
i=-1;
when loop exits since first i's
value is used after that it is decremented
FOR loops are composed of 3 parts:
for ( [Initialization] ; [Exit Condition] ; [Cycle Update] )
[Initialization] is used to assign a value to the loop index before the first iteration
[Exit Condition] is a boolean expression evaluated before each iteration. If it is true another iteration is executed, otherwise the FOR loop ends
[Cycle Update] is the instruction used to update the loop index at each iteration
a classical FOR statement looks like this:
FOR(I = len ; I > END_VALUE ; I--)
What is probably missing in your code is the exit condition, so the cycle update part is interpreted as an exit condition and consequently treated as a boolean expression. When the integer becomes 0 its interpreted boolean value corresponds to FALSE and the loop is ended. Any non-zero value is instead interpreted as a TRUE boolean and allows the execution of another iteration.
When a boolean value is needed, 0
is same as false. Anything other than 0
is true. So, it must stop when i
is 0
, not -1
. You are seeing the value of i
to be -1
because of the post-decrement operator.