Initializing a static array
Hugo Florentino
sysadmin at cips.cu
Thu Mar 8 18:02:07 PST 2012
Hello,
I am a learning D, and so far I am enjoying it. However, since I have a
few doubts I cannot clear just by reading the available documentation, I
registered in this list, so please bear with me if my questions sound a
bit dumb.
So my first doubt is this:
What is the proper D syntax to initialize a static array with
consecutive integers starting with 1?
I know I could simply use "for" like in C, but while reading the web
documentation on arrays, I noticed the vector notation. According to the
documentation, this code:
T[] a, b;
...
a[] = b[] + 4;
is equivalent to this code:
T[] a, b;
...
for (size_t i = 0; i < a.length; i++) a[i] = b[i] + 4;
Now, suppose I declare a static array:
int[100] myarray;
What would be the substitution in vector notation for this code?
for (int i =0; i < myarray.length; i++) myarray[i] = i +1;
I have tried these, and neither seems to work as expected (they simply
assign 0+1 to every element):
myarray[] += 1;
myarray[] = myarray[] + 1;
I also tried using the array as an aggregate in a foreach statement:
foreach(int i, int j, myarray) j = i + 1;
However, it does not work this way because apparently the j variable
seems to work only for reading, not for assigning. I wonder why this
limitation in behavior, if according to the documentation:
"If there are two variables declared, the first is said to be the index
and the second is said to be the value [set to the elements of the
array, one by one]"
So if j refers to the value, the intuitive thing IMHO would be assigning
to each element when one assigns to j. Oherwise one would have to do
something redundant like this:
foreach(int i, int j, myarray) myarray[i] = j = i + 1;
Or maybe this (which renders j useless altogether)
foreach(int i, int j, myarray) myarray[i] = i + 1;
Or even something like this (which works, but misses the advantage of
using the array as an aggregate):
foreach(int i; 0..myarray.length) myarray[i] = i + 1;
Or I am missing something?
Either way, please advice the recommended D way.
Regards, Hugo
More information about the Digitalmars-d
mailing list