1

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
}       

2 Answers2

3

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

ratchet freak
  • 47,288
  • 5
  • 68
  • 106
1

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.

Community
  • 1
  • 1
Gassa
  • 8,546
  • 3
  • 29
  • 49