最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - if x = 3 and z is unassigned, why does z = x-- - --x evaluates to 2? - Stack Overflow

programmeradmin1浏览0评论

if x = 3 and z is unassigned,
why does z = x-- - --x evaluates to 2?

my professor is lecturing about this at the moment, and I'm currently stuck with this dilemma. Unfortunately, no one can explain why it happens.

if x = 3 and z is unassigned,
why does z = x-- - --x evaluates to 2?

my professor is lecturing about this at the moment, and I'm currently stuck with this dilemma. Unfortunately, no one can explain why it happens.

Share Improve this question edited Sep 18, 2012 at 3:10 Bill the Lizard 406k211 gold badges572 silver badges889 bronze badges asked Jun 14, 2012 at 7:47 arscariosusarscariosus 1,3562 gold badges13 silver badges19 bronze badges 9
  • x in post decrement minus x pre decrement – arscariosus Commented Jun 14, 2012 at 7:49
  • 4 is this C# or this is a JavaScript? Choose correct tag, please. – Tigran Commented Jun 14, 2012 at 7:49
  • 1 Duane: The font makes it look weird. Its x-- (x minus minus) minus --x (minus minus x) – Matt Commented Jun 14, 2012 at 7:49
  • 2 very bad practice to have such code lines. There are plenty of other ways to explain the usage of x-- and --x differences. – Steve B Commented Jun 14, 2012 at 7:55
  • 2 Nobody would ever write something like this, I wouldn't use it to explain pre/post decrement, but I'd certainly use it to see if the students really understood the concept – Francesco Baruchelli Commented Jun 14, 2012 at 8:06
 |  Show 4 more comments

3 Answers 3

Reset to default 17

on x--, x = 3, and after that it's 2. on --x, x = 1, because substraction (from 2) is done beforehand.

Therefore, 3 - 1 = 2.

Here is the order of operations, illustrated for better understanding:

  • x-- - --x Hold value of x (lets call it tmpA). tmpA is 3.
  • x-- - --x Decreases x. It is now 2.
  • x-- - --x Decreases x. It is now 1.
  • x-- - --x Hold value of x (lets call it tmpB). tmpB is 1.
  • x-- - --x Performs substruction from calculated values. 3 - 1 = 2.

The -- prefix means the decrement will be done before evaluating the expression and the postfix -- means the decrement will be done after evaluation the expression.

Ok, its pretty simple:

let's add brackets:

z = ( x-- ) - ( --x )

^^ this is how compiler sees your code after tokenizing.

Compiler evaluates equation (right part) from left to right

Now,

x-- is equal to POP the value of x and then decrement it and PUSH back value into a memory. Ok, lets do it:

Current value of X is 3, decremented is 2 - so, in equation we'll get 3, but X will contain new value 2.

--x is equal to decrement X value and then POP this value into equation. Let's do it:

Current value of X is 2 (because previous operation decremented it), and now we want to decrease it once again. 2-1 = 1, got it.

Now, back to whole equation: z = (3) - (1) = 2.

发布评论

评论列表(0)

  1. 暂无评论