wxyz
wxyz

Reputation: 707

for instruction acting not like expected

here's the code which I don't quite understand:

for(int i = 0; i < (i = 1); i++)
            System.out.println("FOR " + i);

I expected this code not to show anything, but instead it outputs 'FOR' one time.

I was thinking that i < (i=1) should compare the value of i with the result of the assignment i=1 which is 1 -> so 1<1 which is false -> exit the loop without showing anything.

Maybe the way this comparison is made is different than I understand it. Thank you!

Upvotes: 0

Views: 49

Answers (3)

Rohit Jain
Rohit Jain

Reputation: 213311

i < (i = 1)

This will be evaluated as: -

0 < (i = 1)  -->   0 < 1  --> true, so for loop executes

On next run, when i++ is executed and i becomes 2 (Since, i was 1 from the (i = 1) assignment on the previous run of loop.)

So, i < (i = 1)

evaluates to: -

2 < 1 --> false.

So, for loop exits.

Note: - In your condition part (i < (i = 1)), before the assignment (i = 1) happens, the LHS has already been evaluated to be 0, and stored in memory. So, it will remain 0. Its all about the order of evaluation. So the assignment i = 1 will not affect the value of expression on LHS.

Upvotes: 2

jlordo
jlordo

Reputation: 37823

I was thinking that i < (i=1) should compare the value of i with the result of the assignment i=1 which is 1

yes, it compares it with what you are expecting. But you initialize int i = 0, thus having 0 < 1 which is true.

Upvotes: 0

Napsteur
Napsteur

Reputation: 94

No, you're true.

i < (i = 1) is the problem cause the assignation (i = 1) is a boolean eguals at true: 1

Upvotes: 0

Related Questions