4

I get very confused at times with the shorthand increment operation.

Since when i was little programming in BASIC, i got some how stuck with a = a+1 which is long painful way of saying 'Get a's current value, add 1 to it and then store the new value back to a'.

1] a = a +1 ; 

2] a++ ;

3] ++a;

4] a +=1;

[1] and [4] are similar in functionality different in notation, right?

2] and 3] work simply differently because of the fact that the increment signs ++ is before and after. Right?

Am I safe to assume the below?

int f(int x){ return x * x;}

y = f(x++) -> for x =2, f(x) = x^2

f(x)     ======> y= 2^2 =4 

x=x+1;   ======> x= 2+1 = 3 



y = f(++x) -> for x =2, f(x) = x^2

x=x+1    ===========> x = 2+1 = 3

f(x)     ===========> y =3^2 = 9
4

3 回答 3

19

Difference is, what the operator returns:

The post-increment operator "a plus plus" adds one, and returns the old value:

int a = 1;
int b = a++;
// now a is 2, b is 1

The pre-increment operator "plus plus a" adds one, and returns the new value:

    a = 1;
    b = ++a;
// now a is 2 and b is 2
于 2013-04-12T14:19:37.813 回答
7

First off, you should read this answer very carefully:

What is the difference between i++ and ++i?

And read this blog post very carefully:

http://blogs.msdn.com/b/ericlippert/archive/2011/03/29/compound-assignment-part-one.aspx

Note that part two of that post was an April Fool's joke, so don't believe anything it says. Part one is serious.

Those should answer your questions.

When you have just an ordinary local variable, the statements x++; ++x; x = x + 1; x += 1; are all basically the same thing. But as soon as you stray from ordinary local variables, things get more complicated. Those operations have subtleties to them.

于 2013-04-12T14:46:48.450 回答
1

1], 3] and 4] are functionally identical - a is incremented by one, and the value of the whole expression is the new value of a.

2] is different from the others. It also increments a, but the value of the expression is the previous value of a.

于 2013-04-12T14:19:15.167 回答