Share/Save/Bookmark Subscribe

Friday, December 31, 2010

Fun with initialization order

Here's something I meant to post ages ago, when I was doing J2ME to Flash conversions, and got caught out by assumptions about the evaluation order of values passed to a method or to initialize an array. It's one of those really subtle issues that had me scratching my head to figure out what had gone wrong in a piece of code.

Consider the following (pseudo)code:
1 2 3 4 5 6 7 8 9 
function evalTest(val1, val2, val3)
{
     print("val1: "+val1+", val2: "+val2+", val3: "+val3);
}

int val = 0;
int arr = { ++val, ++val, ++val };
print("arr: ["+arr[0]+", "+arr[1]+", "+arr[2]+"]");

Now what would you expect the output to be? I had unwittingly assumed the result would consistently be:
arr: [1, 2, 3]
val1: 1, val2: 2, val3: 3

As it turns out, the answer varies from language to language (which is why I got snagged by code working 'correctly' in one language but 'breaking' in another):

Java:
1 2 3 4 5 6 7 8 9 10 11 
int val = 0;
int[] arr = {++val, ++val, ++val};
System.out.println("arr: ["+arr[0]+", "+arr[1]+", "+arr[2]+"]");

val = 0;
evaluationTest(++val, ++val, ++val);

void evaluationTest(int val1, int val2, int val3) {
  System.out.println("val1: "+val1+", val2: "+val2+", val3: "+val3);
}

Result:
arr: [1, 2, 3]
val1: 1, val2: 2, val3: 3
 
Actionscript:
1 2 3 4 5 6 7 8 9 10 
function evaluationTest(val1:Number, val2:Number, val3:Number) {
        trace("val1: "+val1+", val2: "+val2+", val3: "+val3);
}
var val:Number = 0;
var arr:Array = [++val, ++val, ++val];
trace("arr: ["+arr[0]+", "+arr[1]+", "+arr[2]+"]");
 
val = 0;
evaluationTest(++val, ++val, ++val);

Result:
arr: [3, 2, 1]
val1: 3, val2: 2, val3: 1
 
Some others:
C++ undefined:
C# guaranteed to be right to left:

Posted via email from Matt's thoughts

blog comments powered by Disqus
 

Copyright 2007 All Right Reserved. shine-on design by Nurudin Jauhari. and Published on Free Templates

Afrigator