Search⌘ K
AI Features

foreach Loop Properties

Explore the essential features of the foreach loop in D programming. Learn how element copying works, how to modify elements with ref, maintain container integrity, and iterate in reverse. This lesson helps you write effective loops while avoiding common pitfalls.

Counter for containers

The automatic counter in foreach is provided only when iterating over arrays. There are two options for other containers:

  • Taking advantage of std.range.enumerate

  • Defining and incrementing a counter variable explicitly:

size_t i = 0;

foreach (element; container) {
    // ...
    ++i; 
}

A counter variable is needed when counting a specific condition as well. For ...