+ 2

What is the output of this code?

int a = 4; int b = 6; b = a++; Console.WriteLine(++b); I know that the answer is 5 (from trial and error), I just don't understand the logic behind the resolution. When I see this code I see: 6 = a++ (5 because the increment of 4 is 5) Whatever algebra I learned years ago goes straight down the drain. Does b = 6 essentially get overwritten because it's not set as a constant? I also don't understand the relevance of the prefix/postfix ++ in this scenario. Is the purpose of post/prefix similar to that of PEDMAS? Prefix means to increment before the equation, and postfix means to increment after the equation right? So if I'm getting this right: a=4, b=6, x=? a++*b = 25 (4*6+1) ++a*b = 30 ((4+1)*6) That doesn't seem to be the case, but that's where my brain has led me.

13th Dec 2021, 8:16 AM
Alain Sauve
3 Respostas
+ 2
"Does b = 6 essentially get overwritten because it's not set as a constant?" Yes exactly, it was given the value 6 when defining to make the question a little more complex. The line b=a++ assigns 4 to b, then increments a by 1, resulting in b=4 and a=5. Then you print ++b, which increments b by 1 (now b is 5) and returns it, then finally 5 is printed to the screen
13th Dec 2021, 8:45 AM
Rishi
Rishi - avatar
+ 2
Can you come up with a scenario where you would define 2 variables, then increment them in such a way? Which variable has precedence? Why do both a & b get redefined from a single equation? There are essentially 2 separate resolutions to the equation, and it seems foreign to me. The first resolution is converting b to a. 6 now = 4. The following resolution is a now = 5. If the WriteLine was b++ would the output be 4, meanwhile b now = 5? That resolution seems illogical.
13th Dec 2021, 8:54 AM
Alain Sauve
+ 2
This scenario would mostly be used only in quizzes, but I'll provide you one example that I came up with just now Imagine that you want to print an array, and the variable "i" has the current index, then you can do something like the following code snippet: while(i<size){ Console.WriteLine(array[i++]); } Here, the output is the current element, but i now = next index. So this is a case where this post increment feature can be used But ofcourse you can do this by using pre-increment too
13th Dec 2021, 9:43 AM
Rishi
Rishi - avatar