-3
Int y = 0
Int x = 5
y = x++

As compared to doing something like

Int y = 0
Int x = 5
y = ++x

Particularly, I'm asking how the position of the post increment generally affects the output

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
Bob John
  • 3,688
  • 14
  • 43
  • 57

5 Answers5

0

If the prefix/postfix operator is part of an expression or function evaluation, it determines the order in which the variable is modified, either before the evaluation (prefix) or after the evaluation (postfix).

In this first case,y is assigned before x is incremented.

int y = 0;
int x = 5;
y = x++;

In this second case, x is incremented first, then y is assigned.

int y = 0;
int x = 5;
y = ++x;

Beware: if used in an array index on both sides of an equation, the behavior may be undefined.

Community
  • 1
  • 1
Peter Gluck
  • 8,168
  • 1
  • 38
  • 37
0

x++ increments x after the operation.

Int y = 0 Int x = 5 y = x++

Y would be equal to 5 while also setting x to equal 6.

Int y = 0 Int x = 5 y = ++x

Y would be equal to 6, X would also be equal to 6.

X33
  • 1,310
  • 16
  • 37
0

In the first case, y = x++, x is post-incremented. That is to say x is increased in value after its value is assigned to y.

y = 5 and x = 6.

In the second case, y = ++x, x is pre-incremented. x is increased in value before its value is assigned to y.

y = 6 and x = 6

byteherder
  • 331
  • 2
  • 9
0

When the operator is before variable, it does (and supposed to when one writes own operators) perform an operation and then return result.

int x = 1 ;
int y = x++ ; // y = 1, x = 2
int z = ++x ; // x = 3, z = 3

I would suggest using temporary programs and outputs to see how things work. Of course a good book is the best ;)

Grzegorz
  • 3,207
  • 3
  • 20
  • 43
0
pre-increment (++X): means that the value of X will be incremented before it gets assigned.
 in your example, value of Y will be 6 because X gets incremented first (5+1) then gets assigned to Y.

post-increment (X++): means that the value of X will be incremented after it gets assigned.
in your example, value of Y will be 5 because X gets incremented after it is assigned to Y.

You can compare these as:
++X = in-place increment
X++ = increment happens in a temporary location (Temp=5+1) which gets assigned to X (X=Temp) after Y is set to its current value (5).

Y = X++ can be represented as:
  > Temp = X+1
  > Y = X
  > X = Temp
Java Spring Coder
  • 1,017
  • 3
  • 12
  • 20