Most programmers (Flash and otherwise) are familiar with the increment operator ‘++‘ which is used to increase the value of a variable by 1.
Most programmers are also familiar with the ‘+=‘ addition assignment notation for increasing a variable by a value. For example c+=5 will increase the value of c by 5.
Up until a few weeks ago I was under the impression that c++ and c+=1 were functionally the same but a rather interesting bug has taught me otherwise.
In a game we were developing we had to select a random element from an array and increment the value of that element by 1. Naturally enough we did something like:
function randomInt( min:int, max:int ): int
{
return Math.floor( Math.random()*(max - min) ) + min;
}
var arr:Array = [ 5, 7, 9, 11, 13 ];
trace("PRE: " + arr);
arr[ randomInt(0, arr.length) ]++;
trace("POST: " + arr);
Run the above code and you will get something along the lines of:
PRE: 5,7,9,11,13
POST: 5,7,10,11,13
as you would expect
At some point it was decided that instead of increasing the random element by 1 it should be increased by 2. So the incrementing code was modified to ‘+=2‘ but for illustration purposes will just change it to ‘+=1‘:
function randomInt( min:int, max:int ): int
{
return Math.floor( Math.random()*(max - min) ) + min;
}
var arr:Array = [ 5, 7, 9, 11, 13 ];
trace("PRE: " + arr);
arr[ randomInt(0, arr.length) ]+=1;
trace("POST: " + arr);
Run the above code and some of the time it works (particularly with small arrays) but most of the time you get odd results:
PRE: 5,7,9,11,13
POST: 14,7,9,11,13
After a bit of head scratching we realised that
arr[ randomInt(0, arr.length) ]+=1;
was being compiled as if it was:
arr[ randomInt(0, arr.length) ] = arr[ randomInt(0, arr.length) ] + 1;
In other words, one random element of the array was being set to 1 more than another random element of the array.
What this illustrates is that ‘++‘ is (true to its definition) compiled as a unary operator that modifies the value of the referenced variable, whereas ‘+=‘ is simply shorthand notation and is evaluated as if written in long form ie. c = c + 1. An insignificant difference when dealing with integers but quite significant when dealing with array elements.
Suite 19, 2 Portrush Road,
Payneham, South Australia,
Australia
(+61) 8 8337 6140
