3

I've just started with C#. I was reading about operator precedence and there was a part about precedence of unary operator. I've tried to imagine the situation where I can see such stuff. And for example:

int a = 5;
a = -a++;

Example is stupid but still... "Unaries" are right-associative. I expected a result of -6 but it's -5. I understand that "++" returns first then increments. But WHAT it increments if not "a"? Why "a" is not affected?

Thanks =]

stkirill
  • 39
  • 4
  • 3
    The variable `a` is incremented. It will contain the value `6` for a short while, but then that value will be replaced by the `-5` that you store in it. The value of the expression `a++` will be `5`, and that will be used in the expression `-a++` to produce the value `-5`. – Guffa Jul 22 '15 at 21:14
  • Shar1er80 is correct, -5 is the expected result – Johnie Karr Jul 22 '15 at 21:16
  • 1
    @Shar1er80: No, `++` does *not* happen after the assignment. It happens after the result of `a++` has been determined, but *before* the unary minus is applied to the result, and before the assignment. – Jon Skeet Jul 22 '15 at 21:21
  • 1
    @JohnieKarr: -5 is the correct result, but Shae1e80 is incorrect about the reason for it. – Jon Skeet Jul 22 '15 at 21:22
  • Your expected result of -6 would be "a = -++a;" or "a = -(a+1);" – Shar1er80 Jul 22 '15 at 21:23
  • 1
    Also have to +1 Jon Skeet's comment, BECAUSE IT'S @JonSkeet! :-) – Shar1er80 Jul 22 '15 at 21:23
  • The order of things in this statement is as follows: First the value of `a` is read, which is 5. We then add one to the 5, getting 6, and then store that back into the `a`. `a` is now 6. We then take the 5 we got when we first read `a` and negate it, getting -5. We then assign that to `a`. `a` ends up as -5. – Lasse V. Karlsen Jul 22 '15 at 22:03
  • 1
    @JonSkeet...big fan...thrilled to see you type my name :). Anyway, I was just saying that -5 is the expected result, didn't intent to agree with the reasoning. Thanks for the clarifying comment though. :) – Johnie Karr Jul 23 '15 at 02:39
  • 1
    @lasse-v-karlsen: 1. `a++` returns 5 (to stack?) and writes 6 to actual `a` value. At this moment `a` is really equals to 6. 2. `-` works with the value 5 (from the stack? =) and writes result to `a`. Result of `a++` is not `a` itself. It's some temporary value in memory and the rest of the expression continues to work with that. Correct? – stkirill Jul 23 '15 at 07:46

0 Answers0