Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# post increment and pre increment

Tags:

c#

.net

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
like image 516
Athapali Avatar asked Nov 27 '22 17:11

Athapali


2 Answers

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
like image 98
metadings Avatar answered Dec 15 '22 13:12

metadings


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.

like image 30
Eric Lippert Avatar answered Dec 15 '22 15:12

Eric Lippert