C# post increment and pre increment

二次信任 提交于 2021-02-04 18:29:07

问题


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

回答1:


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



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/15973628/c-sharp-post-increment-and-pre-increment

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!