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 | Show 4 more comments3 Answers
Reset to default 17on 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
.
C#
or this is aJavaScript
? Choose correct tag, please. – Tigran Commented Jun 14, 2012 at 7:49x--
(x minus minus) minus--x
(minus minus x) – Matt Commented Jun 14, 2012 at 7:49x--
and--x
differences. – Steve B Commented Jun 14, 2012 at 7:55