www.webdeveloper.com
Results 1 to 5 of 5

Thread: Question about auto increment auto decrement unary operator syntax

  1. #1
    Join Date
    Mar 2012
    Posts
    29

    Question about auto increment auto decrement unary operator syntax

    If I run the following code in firebug the output equals 0
    Code:
    y = 5;
    x = 0;
    z = 1;
    newnum = y++ + ++x + x++ + z++ - z++ - y--;
    If I test x, y and z on their own in firebug the output is -

    Code:
    y++;   //  5
    ++x;  // 1
    x++;  // 0
    z++;  // 1
    y--;   // 5
    this makes newnum look like

    newnum2 = 5 + 1 + 0 + 1 - 1 - 5; // which outputs 1 in firebug

    Is there a particular reason the output of newnum is 0 rather than 1?

    Best regards Maxwell

  2. #2
    Join Date
    May 2006
    Location
    Somewhere behind your screen
    Posts
    1,672
    y = 5;
    x = 0;
    z = 1;

    newnum = y++ + ++x + x++ + z++ - z++ - y--;

    in human language this means:
    (return y which is 5, then do y+1) ---------> 5
    +
    (do x+1, then return x) ---------> 1
    +
    (return x, then do x + 1) ---------> 1
    +
    (return z, then do z+1) ---------> 1
    -
    (return z, then do z+1) ---------> 2
    -
    (return y, then do y-1) ---------> 6

    so we have 5+1+1+1-2-6=0

  3. #3
    Join Date
    Mar 2012
    Posts
    29
    I still don't understand how y-- can equal 6 when it originally contained 5

  4. #4
    Join Date
    Oct 2010
    Location
    Versailles, France
    Posts
    1,272
    Y was originally 5, but it has been modified to 6 !

  5. #5
    Join Date
    May 2006
    Location
    Somewhere behind your screen
    Posts
    1,672
    again. we have

    y = 5;
    x = 0;
    z = 1;

    newnum = y++ + ++x + x++ + z++ - z++ - y--;

    y++ means: take var y (which is 5 now) for the newnum math adding operation, then increase it by 1
    the same with all var++
    but
    ++x means: increase x by 1, then take it (being 1 now, not 0) for the newnum math adding operation
    Last edited by Padonak; 06-15-2013 at 01:51 AM.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles