sábado, 20 de agosto de 2011

Array initialization fun-ness

You don't normally see people publish a TODO item on their blog but this one is really bugging me:

//TODO: Find a simple way of initialization and assigning a 'static' array of integers (or strings!).

Let's hit the MSDN first and see the four ways to declare our int arrays:
// A dynamic array of integers
int i[]; 
 
// A fixed-length real array with 100 elements
real r[100]; 
 
// A dynamic array of dates with only 10 elements in memory
date d[,10]; 
 
// A fixed length array of NoYes variables with 100 elements
// and 10 in memory
noYes e[100,10]; 
That's sweet but we're not assigining the values to these arrays. And it's this which is really annoying me. This is what we would like to do in our psuedo non X++ compliant code:
int     iPeso[13] = {5, 4, 3, 2, 1, 9, 8, 7, 6, 5, 4, 3, 2};
However, I found an interesting comment in the aforementioned MSDN that leads me to believe that it can't be done:

"You use a separate statement to initialize each element in an array."

Sadness:
    int     iPeso[13];
    ;
    iPeso[1]   = 5;
    iPeso[2]   = 4;
    iPeso[3]   = 3;
    iPeso[4]   = 2;
    iPeso[5]   = 1;
    iPeso[6]   = 9;
    iPeso[7]   = 8;
    iPeso[8]   = 7;
    iPeso[9]   = 6;
    iPeso[10]  = 5;
    iPeso[11]  = 4;
    iPeso[12]  = 3;
    iPeso[13]  = 2;
My investigations with the Array class however brings us one small point of shining light to the blog entry, from Jay Hofacker:
//To reset all elements of an array type, assign a value to element 0
int myArray[10];
;
myArray[0]=0; //reset all elements of the array to their default value
As a final thought, I'm wondering if we should use the container class to save our fingers, disregarding the conversion between data types of each iteration:
container cPeso = [5, 4, 3, 2, 1, 9, 8, 7, 6, 5, 4, 3, 2];

No hay comentarios:

Publicar un comentario