Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

c#

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.

like image 312
arscariosus Avatar asked Jun 14 '12 07:06

arscariosus


2 Answers

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.

like image 157
Samuli Hakoniemi Avatar answered Sep 28 '22 13:09

Samuli Hakoniemi


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.

like image 37
SimpleVar Avatar answered Sep 28 '22 13:09

SimpleVar