How is the following for loop different from original?
Why after initialization, it checks for the condition?
Why such behavior and what are other such tricky behaviors of for
loop?
class FooBar
{
static public void main(String... args)
{
for (int x = 1; ++x < 10;)
{
System.out.println(x); // it starts printing from 2
}
}
}
Output:
2
3
4
5
6
7
8
9
++x
increments the value of x
. As a result, two things are happening:
If you want values from 1 to 9, use the standard loop:
for (int x = 1; x < 10; ++x) { ... }
The effects of prefix and postfix operators has been discussed and explained in detail elsewhere, this post, for example.
The increment of x
is combined with the condition. Normally, the increment is performed in the third section of the for
loop, which is a statement executed at the end of an iteration.
However, the condition is checked at the beginning of the loop. It's an expression, not a statement, but as you can see, that doesn't stop someone from inserting a side-effect -- the pre-increment of x
.
Because x
starts out as 1
, the condition increments it to 2
before the first iteration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With