+ 1
Incrementing in java
I am getting confused every time I try understand the logic of ++ in this code Please can someone make it clear and explains especially i0 and i1 why they have the same output https://code.sololearn.com/ccpsVA9kVC25/?ref=app
5 Réponses
+ 1
I given in comments what values get replaced for instruction step by step and also gave an extra clear example for simplicity with explanation. that applies to all.
i0 => j0++ is replaced by 0 then j0 gets incremented so now j0=1 so next j0*5 replaced as 1*5 totally 0+5=5
i2=>j2*5+ j2++ => 0*5+0 and next j2 is incremted so 0+0=0 ,and j2=1
if you have like j2*5+ j2++ + j2++ then 0*5+0+1, but last j2=2
its simply, post increment ex: x++ , first it uses its value then increments
pre increament : ++x , first it increments its value next it uses its value
check
x=2
y=x++; // then y=2, x=3(x is assigned to y first then increaments)
x=2
y=++x ; //y=3,x=3
+ 3
The compiler doesn't give an error and seems to interpret the expression from left to right BUT you really shouldn't increment and use a variable in the same line. That is, DON'T DO
int i0 = j0++ + j0;
+ 3
Jayakrishna🇮🇳 yes you are right!. .
I was really confused so it takes me time to understand the answer very well !
Thank you so much for explaining I appreciate 🤩
+ 1
int j0=0,j1=0,j2=0,j3=0,j4=0,j5=0;
int i0=j0++ +j0*5; //=>0+1*5=5
int i1=j1+ ++j1*5; //=>0+1*5=5
int i2=j2*5 + j2++; //=>0*5+0=>0, j2=1
int i3=j3*5 * ++j3; //=>0*5*1=>0, j3=1
int i4=++j4 + j4*5; //=>1+1*5=6
int i5=j5+ j5++*5; //=>0+0*5=0 , j5=1
if x=1; then in
x++ + ++x => 1+3=4
=>here x++ post increament, the value first uses, next increaments so uses 1 and increments then x=2 so next in preincrement ++x, first is incremented, then it is uses its value so ++x is replaced by 3 , then x=3 and result is 4
+ 1
you're welcome..Hadjer