Last modified on 15 August 2010, at 20:21

A Beginner's Guide to D/Conditions and Loops/Complex Iteration: The for Loop

The most complicated loop statement that D provides is the for loop. The for loop is borrowed directly from C, and shares its syntax. It has the following form:

for(statements; conditional; statements) { body }

The first set of statements are separated by commas, and are executed before the loop begins. Variables can be declared in these statements. This is usually used to initialize an index variable. The conditional is a Boolean value, and is executed before each iteration of the loop. The body is only executed as long as the conditional remains true. The last set of statements are executed after the body, and usually increments an index variable.

The following is the typical use of the for loop:

import std.stdio;
void main()
   int arr[] = [1, 2, 3, 4, 5];
   for(size_t x=0; x<arr.sizeof; x++) {
      writefln("%d", arr[x]);

However, more complicated for loops are possible. For example, a for loop can iterate over two arrays, in opposite directions, at the same time:

void reverse_array(out int[] dest, int[] src) {
    dest.length = src.length;
    for(size_t dx=0, sx=src.length-1; dx < dest.length; dx++, sx--) {
        dest[dx] = src[sx];