Control flow statements
D includes the traditional loop and conditional statements found in other C-family languages. It also supports the infamous goto
statement. It has a couple of other useful statements, such as a built-in foreach
statement and a rather unique scope
statement. In this section, we're going to look at examples of each of the first two. Because of their relation with exceptions, scope
statements are included in detail in the next chapter.
Traditional loops
In terms of looping constructs, we have for
, do
, and do-while
. The syntax and behavior should be familiar. Here is an example of each iterating over an array:
auto items = [10,20,30,40,50]; for(int i=0; i<items.length; ++i) writeln(items[i]); int i = 0; while(i < items.length) writeln(items[i++]); i = 0; do { writeln(items[i++]); } while(i < items.length);
No surprises there. The braces are optional with for
and while
when they only contain one statement. When a loop with an empty body is desired, the...