Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Control flow logic in for loop

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

like image 511
Shubham Kharde Avatar asked Dec 25 '22 16:12

Shubham Kharde


2 Answers

++x increments the value of x. As a result, two things are happening:

  1. The value being checked for the for-loop condition (i.e., the inequality), is already incremented, and
  2. This incremented value is what gets printed within the loop.

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.

like image 170
Chthonic Project Avatar answered Jan 07 '23 06:01

Chthonic Project


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.

like image 35
rgettman Avatar answered Jan 07 '23 06:01

rgettman