Loops

D provides four loop constructs.

1) Classical for loop

The classical for loop known from C/C++ or Java with initializer, loop condition and loop statement:

for (int i = 0; i < arr.length; ++i) {
    ...

2) while

while loops execute the given code block while a certain condition is met:

while (condition) {
    foo();
}

3) do ... while

The do .. while loops execute the given code block while a certain condition is met, but in contrast to while the loop block is executed before the loop condition is evaluated for the first time.

do {
    foo();
} while (condition);

4) foreach

The foreach loop which will be introduced in the next section.

Special keywords and labels

The special keyword break will immediately abort the current loop. In a nested loop a label can be used to break of any outer loop:

outer: for (int i = 0; i < 10; ++i) {
    for (int j = 0; j < 5; ++j) {
        ...
        break outer;

The keyword continue starts with the next loop iteration.

In-depth

rdmd playground.d