Reputation: 87
b = 5;
loopiterations = 0;
while (b-- > 0) { // Use a postfix decrement
loopiterations++;
}
System.out.println("Postfix decrement operator used, loopiterations = " +
loopiterations + ", b = " + b);
The result is
Postfix decrement operator used, loopiterations = 5, b = -1
I don't understand why the value of b is -1. The value of b starts from 5 (after while loop it's value is 4) and then ends at 1 ( after the while loop it is 0) and then the iteration from 5 to 1 is 5.If how I think is right, why is the value of b is -1 after looping. Thank you.
Upvotes: 5
Views: 316
Reputation: 51433
This block of code
while (b-- > 0) {
// do something
}
is semantically the same as
while (b > 0) {
b--;
// do something
}
b--;
The loop while (b-- > 0)
exits as soon as b == 0
, but because of the post decrement operation b
will be one last time decrement and hence b
will have the value of -1
when printing.
Upvotes: 3
Reputation: 131
**postfix increment or decrement actually happens after using value**,
the initial value of b is 5 so in the first iteration 5 is checked for condition after the last iteration, b becomes 0 after its value (1 at time of comparison) has been decremented, then 0 is checked but the condition is false but due to postfix decrement it's value becomes -1.
postfix -> first use value then decrement or increment that's how it works
Upvotes: 2
Reputation: 155
This is because when b == 0
, the postfix will return false
and your while loop will terminate. However, the postifx will still subtract one from b
. Therefore, the loop is executed 5 times, and iterations = 5
. However, b
is decremented 6 times.
Upvotes: 1