+ 1

Why are there different outputs when I change the order in the Code of different ways of incrementing by 1 ?

example 1 int x=0; System.out.println(x); x=x++; System.out.println(x); x=x+1; System.out.println(x); ×+=1; System.out.println(x); // prints 0,0,1,2 example 2 int x=0; System.out.println(x); x=x+1; System.out.println(x); x+=1; System.out.println(x); ×++; System.out.println(x); // prints 0,1,2,3 Depending on wether x++ is the first operation (example1) or the last Operation (example 2) it will increment x ? edit: line 3 I messed up. didn't mean x=x++ but only x++. Then the output is the same in both.

20th Dec 2016, 10:37 AM
eternallatesummer
1 Answer
+ 2
Because "x++" means "add 1 after current operation" while "++x" increments before operation. x = 1; // x is 1 x = x++; // x is still 1 cout << x; // x is 2 You need a valid operation to make x++ work or make it as ending operation.
20th Dec 2016, 10:51 AM
Maksym ZieliƄski
Maksym ZieliƄski - avatar