+ 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?

15th Feb 2018, 12:16 PM
Christopher Reineborn
Christopher Reineborn - avatar
4 ответов
+ 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.
15th Feb 2018, 12:23 PM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 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
15th Feb 2018, 1:53 PM
SQrL
SQrL - avatar
+ 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.
15th Feb 2018, 12:33 PM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
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. ".
16th Feb 2018, 2:44 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar