Question

What are the indices these two foreach loops will iterate over:

struct Section{}
Section[] sections;

// assuming we have 10 sections
foreach(ref s; sections[0..$/2+1]) {
    // do something
}       

foreach_reverse(ref s; sections[$/2..$])
{
    // do something
}       
Was it helpful?

Solution

the first will iterate over 0-sections.length/2+1=6 (exclusive) and the second will iterate 10-5

the $ in the index refers to the length of the array

and the array[a..b] notation expands to array.opSlice(a,b) that returns a partial view of the array

OTHER TIPS

In D, an empty struct has a size 1. The rationale is the same as in C++: see here for a relevant question and the rationale. So, your array will contain dummy 1-byte elements.

Let us check this behavior:

import std.stdio;

struct Section{}
Section[] sections = new Section [10];

void main () {
    foreach(ref s; sections[0..$/2+1]) {
        writeln (&s);
    }
}

To me, this prints:

42208C
42208D
42208E
42208F
422090
422091

which are consecutive addresses in memory.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top