Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between i++ vs i=i+1 in an if statement? [duplicate]

For the 1st code,

int i = 1;
while (i < 10)
    if ((i++) % 2 == 0)
        System.out.println(i);

The system outputs: 3 5 7 9

For the 2nd code,

int i = 1;
while (i < 10)
    if ((i=i+1) % 2 == 0)
        System.out.println(i);

The system outputs: 2 4 6 8 10

Why are the two outputs different but the formula is the same?

like image 255
bwuxiaop Avatar asked May 16 '15 21:05

bwuxiaop


2 Answers

If you use i++, the old value will be used for the calculation and the value of i will be increased by 1 afterwards.

For i = i + 1, the opposite is the case: It will first be incremented and only then the calculation will take place.

If you want to have the behavior of the second case with the brevity of the first, use ++i: In this case, i will first be incremented before calculating.

For more details and a more technical explanation, have a look at the docs for Assignment, Arithmetic, and Unary Operators!

like image 118
TimoStaudinger Avatar answered Sep 22 '22 16:09

TimoStaudinger


i = i+1 will increment the value of i, and then return the incremented value.

i++ will increment the value of i, but return the original value that i held before being incremented.

like image 41
Llogari Casas Avatar answered Sep 24 '22 16:09

Llogari Casas