May 27
Test your brain and ActionScript programming insight with this simple question: What's the output of the following trace statement?
Actionscript:
-
var i = 1;
-
i += i++ + ++i;
-
trace("i=" + i);
Add to Bloglines - Digg This! - del.icio.us - Stumble It! - Twit This! - Technorati links - Share on Facebook - Feedburner
Christophe Herreman is a software developer living in Belgium. He's working on high-end Flex and AIR solutions at
May 27th, 2006 at 12:02 pm
Haha, nice!
I guessed the correct result.
May 27th, 2006 at 4:42 pm
In actionscript, javascript, java and vbscript it is 5
var i:Number;
i = 1;
i += i++ + ++i;
trace(”i = “+i);
i = 1;
i = i+i+(i+1);
i++;
trace(”i = “+i);
i = 1;
i = 3*i+2;
trace(”i = “+i);
In php and c++ however this would be 7 …
‘;
$i = 1;
$i++;
$i = $i + $i + $i;
$i++;
echo ‘i = ‘, $i, ”;
$i = 1;
$i = (3 * ($i + 1)) + 1;
echo ‘i = ‘, $i, ”;
?>
And in ruby it would be 3.
i = 1
i += i++ + ++i
puts ‘i = ‘ + i.to_s
i = 1
i = 3 * i
puts ‘i = ‘ + i.to_s
My head hurts.
May 27th, 2006 at 5:49 pm
It seems that only actionscript, javascript, java and vbscript does this right ?
i = 1
i += i++ + ++i
first operate on the right side :
1st operation i++ => right_ans = 2
2nd operation + (i is still 1) => right_ans = 2 + 1 = 3
3rd operation ++i => right_ans = 3 + 1 = 4
then operate on the left side :
i = i + right_ans = 1 + 4 = 5
May 29th, 2006 at 1:48 am
@ caprica: Depends on your definition of right.
Actionscript:
var i = 1;
i += ++i;
trace(i); // traces 3
//is equivalent to
var i = 1;
var oldi = i;
var x = ++i;
i = oldi + x;
trace(i); //traces 3
Php:
$i = 1;
$i += ++$i;
echo ‘i = ‘, $i, ‘<br>’; // echos 4
//is equivalent to
$i = 1;
$x = ++$i;
$i = $i + $x;
echo ‘i = ‘, $i, ‘<br>’; // echos 4
Ruby:
Ruby doesn’t support the increment operator.
So you can write ++ all you want, it will just ignore you.
Each of these approaches makes sense, they just happen to differ.