문제

Two examples of variable declarations are listed:

Example 1:

x = 10;
y = ++x;

Example 2:

x = 10;
y = x++;

The book said that in Example 1 y equals 11, and in Example 2 y equals 10. I think I get why and here's my reasoning, so please let me know if I've got this and/or if there's a more concise way of thinking about it.

In the first example, y equals 11 because it's simply set to equal "x + 1" since the increment operator comes first, whereas in the second example y is set to be equal to the original declaration of x and then the increment operation occurs on x separately. It seems to make sense since visually in Example 2 the variables are both right next to the equals sign and then the "x + 1" operation would occur as an afterthought to that equation with no effect on y.

도움이 되었습니까?

해결책

You're right.

y=++x

means: x++; y=x;

HOWEVER,

y=x++;

means: y=x; x++;

다른 팁

I think you have got it but it can be understood in simpler words.

y = x++;

Increment x after this line. Result is

y = 10, x = 11

Whereas in

y = ++x;

Increment x before this line. Result is

y = 11, x = 11

Golden rule:

Prefix increment/decrement (++x or --x) have right-to-left associativity.

Postfix increment/decrement (x++ or x--) have left-to-right associativity.

x = 10

if (x++ == 11) {        
    // Post increment
}


if (++x == 11 ) {
    // Pre increment
}

So in you case:

Example 1:

x = 10;
y = ++x;

Original value of x (here 10) is incremented first and then assigned to y.

Example 2:

x = 10;
y = x++;

Original value of x is first assigned to y and then incremented (to 11).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top