+ 2
Explain the increment to me
Hi, just got into some C# programming and I am doing very well. However I just can't for the love of my life understand this piece of code: int a = 4; int b = 6; b = a++; Console.WriteLine(++b); //Outputs 5 Can someone explain it to me?
4 Answers
+ 4
a++ = Postfix Operation. Adds one to a but returns original value of a. (Before the addition).
Thus, b = a++ makes b = 4, a = 5.
++b = Prefix Operation. Adds one to b and returns final value of b. (After the addition).
Thus ++b returns 5.
+ 3
Based on my code, I think the following is true:
b=++a==a+=1
Which means b is set to a after a as been increased by 1.
However b=a++==a+1
Which means a remains unchanged, but b is now 1 greater than a.
https://code.sololearn.com/ctEyrTfhNI61/?ref=app
+ 1
Actually, ++a would save a 5 into b.
The operators work like this:
var++
-> Copy var into a temp variable.
-> Increment var by 1 (var+=1).
-> Return the temp variable.
Thus, b=a++; translates to b=a, but a in memory gets incremented by one, and b gets the old value.
++var
-> Increment var by 1. (var+=1).
-> Return var itself.
Thus b=++a; translates to b=(a(old)+1), as a(new) is now a(old)+1.
0
@SQrL
In the second statement, you wrote:
"However b=a++==a+1
Which means a remains unchanged, but b is now 1 greater than a. "
But if you ran your code, you can see that the the first b=++a; made both a and b as 5, but the second b=a++; made b retain 5, while a became 6.
So I think in the above statement, you meant:
"However b=a++==a+1
Which means a is 1 greater than itself, but b is still the old a. ".