You have to understand how expressions evaluate. The pre- and post-increment (and decrement) operators change the variables value, but the variable plus the operator constitute and expression who's value varies depending upon the placement of the ++. Essentially, the value of the expression $i++ is original value of $i and $i is incremented by 1. The value of the expression ++$i is new value of $i after $i is incremented by 1.

$i = ++$i + $i++;

In the above example, we evaluate the expression right to left. The expression, $i++, evaluates as zero, even though $i is now 1. The second expression, ++$i, evaluates as 2 (since $i is now 1) and 2+1 equals 3.

$i = $i++ + ++$i;

Pretty straightforward now. The rightmost ++$i evaluates as 1 and $i is set to one. The $i++ also evaluates to 1 (remember, with a post-increment operator doesn't change the return value of the expression, just the variable -- confused yet? :). So, 1 + 1 equals two.

Cheers,
Ovid

Update: Got the concept right, but I evaluated in reverse order. Whoops! Juerd is right.

Update2: Okay, I'm smoking crack. If things are evaluated left to right, then the following is true:

$ perl -e 'print 1-3+2' 0

Well, it turns out that this is true. If it were evaluated right to left, then the answer would negative four. What I think is going on (though I can't prove it offhand) is that built-in unary operators are evaluated right to left, and then the rest of the expression is evaluated based upon precedence rules, if any. Anyone want to shed light on this?

Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.


In reply to Re: $i=$i++ by Ovid
in thread $i=$i++ by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.