MegaZone (zonereyrie) wrote,

Coder geeks

This question was sent out at work by a co-worker:
Solve this in your head: What does the following code display, and why?

$i = 1;
$i += $i++ + ++$i;
echo 'i=', $i;

Bonus question: Is the result always the same in other programming languages (JavaScript, Java, C#, ...; provided the syntax is adapted to the host language :))? Why (not)?

Oh hell...

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

OK, First the pre-increment should run, making $i = 2. 2 += 2 + 2 is 6. Then the post-increment will run, making it 7.

I would *hope* the results are the same, since the rules of precedence are fairly universal. But I wouldn't be shocked to find out they aren't the same.

I've just got to check it out...

PHP: 7
Perl: 7
JavaScript: 5 ... 5? WTF?! (And I ran it in FireFox and IE - same result.)

I bet JavaScript does the pre-increment but doesn't update the other slots, which would make it 1 += 1 + 2 so it is 4, then post-increment would make it 5. That would explain it - but it doesn't make it any less stupid.

So, who wants to try it in other languages? ;-)

BTW, the perl and JavaScript I used:
$i = 1;
$i += $i++ + ++$i;
print "i=" . $i . "\n";

<script type="text/javascript">
$i = 1;
$i += $i++ + ++$i;
document.write("i=" + $i);
Tags: code, geek, quiz
  • Post a new comment


    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

    Your IP address will be recorded