+ 1

Can one explain this?

int x = 0; int z = x++ + x++; Expected behaivour: x = 2, z = 0. Compiled: x = 2, z = 1. Why was z incremented when x was both postfix?

19th Feb 2020, 2:26 PM
CapCode
4 Respuestas
+ 4
The first postfix affects the second one. It might look like it should be 0, but in fact the first postfix changes the value of x to 1, so the second time you call it, x++ will be 1 and not 0. EDIT: A better way to see this is by using variables. int x = 0; int z1 = x++; // so z1 = 0, and x = 1 int z2 = x++ // since x = 1, then x++ returns 1, and x becomes 2 int z = z1 + z2 = 0 + 1 = 1
19th Feb 2020, 2:39 PM
Aymane Boukrouh
Aymane Boukrouh - avatar
+ 1
Prathvi you explained the wrong output..
19th Feb 2020, 2:42 PM
Aymane Boukrouh
Aymane Boukrouh - avatar
+ 1
Aymane Boukrouh Thank you, I think I get it now. Always thought that postfix will increment only after the statement, no matter what.
19th Feb 2020, 7:39 PM
CapCode
- 1
x++ return the value of x than increment means int x=0 int z= 0/* x=1*/+ 1/*x=2*/; So x= 2 and z=1 Like x=0 z=x++;//z=0 and x=1
19th Feb 2020, 2:40 PM
Prathvi
Prathvi - avatar