i += i++ + ++i;

General Add comments

Test your brain and ActionScript programming insight with this simple question: What's the output of the following trace statement?

Actionscript:
  1. var i = 1;
  2. i += i++ + ++i;
  3. trace("i=" + i);


Add to Bloglines - Digg This! - del.icio.us - Stumble It! - Twit This! - Technorati links - Share on Facebook - Feedburner
 

No Responses to “i += i++ + ++i;”

  1. Philippe Says:

    Haha, nice!
    I guessed the correct result.

  2. Kristof Says:

    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.

  3. caprica Says:

    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

  4. Kristof Says:

    @ 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.

Leave a Reply

WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Login