Daze

Music Code Words

Archive for the ‘ code ’ Category

i++ vs ++i The Eternal Struggle!

no comment

So the other day i encountered a curious thing — if you create the following (not recommended) code:


$i=1;
$i=++$i * $i++ * ++$i;
echo "$i";

what do you think the value of $i would be?

according to what i figured:

$i starts out as ‘1’ then the ++$i makes the value 2
then the value of $i is 2 for the purpose of the multiplication
then is post incremented by the $i++ (making it 3)
then the ++$i makes the value 4
$i is then assigned the value as expressed: 2 * 2 * 4

which is a value of 16

but this is only true in C#,  javascript,  java,  and php!

in perl we get a value of 24, but this is due to perl using ++$i in all cases giving us an expression of 2*3*4 (all values of $i are pre-incremented)

in C++ it’s a whole other kettle of fish — it seems to depend on the compiler.

effectively, C++ figures out the final value of $i then post increments it (because of the $i++).

this gives us a value of 13 (2*2*3 = 12 then the post increment makes it 13)
i saw this behaviour using g++

*OR*

this gives us a value of 28 (2*3*4 = 27 then the post increment makes it 28)
this behaviour was in visual studio

no wonder making constructs like ++$i * $i++ * ++$i are frowned upon!

Exciting Calendar

November 2017
M T W T F S S
« Oct    
 12345
6789101112
13141516171819
20212223242526
27282930