[ACCEPTED]-What is the difference between x++ and ++x-c++

Accepted answer
Score: 23

x++ executes the statement and then increments 2 the value.

++x increments the value and then 1 executes the statement.

var x = 1;
var y = x++; // y = 1, x = 2
var z = ++x; // z = 3, x = 3
Score: 9

x++ returns x, then increments it.

++x increments 1 x, then returns it.

Score: 8

++x is higher in the order of operations than 2 x++. ++x happens prior to assignments, but x++ happens 1 after assignments.

For exmaple:

var x = 5;
var a = x++;
// now a == 5, x == 6

And:

var x = 5;
var a = ++x;
// now a == 6, x == 6
Score: 2

If you write y = ++x, the y variable will be assigned 4 after incrementing x.
If you write y = x++, the 3 y variable will be assigned before incrementing 2 x.

If x is 1, the first one will set y to 2; the 1 second will set y to 1.

More Related questions