Monthly Archives: November 2015

loops

D supports the common for / while / do-while statements.

for

while

do-while

For convenience, D has foreach and foreach_reverse.

foreach

The code above prints the square of the numbers in the range [0, 10). Notice that the range is inclusive/exclusive, so 10 is not included.
Also note that we didn’t write i‘s type, as it is automatically infered, but you can write it explicitly if you’d like.

You can also iterate over arrays:

But what if’d you like to print the indices of the even numbers?
Fortunately, D’s foreach can provide you with the index as well!

foreach_reverse

foreach_reverse works like foreach but in reverse order. Using the previous example:

As expected, the same results are printed, in reverse order.

Things to remember

  • for/while/do-while work just like in C, C++
  • foreach / foreach_reverse are more convenient forms of for
  • foreach / foreach_reverse loops can also provide you with the index in the form foreach (index, element)

if statement

Your familiar if-statement

D’s if-statement syntax is the same as other languages with C-style cyntax (C, C++, Java, etc).

Where expression is any expression that can be converted to a boolean value.
As it turns out, a lot of expressions can be converted to a boolean expression.

  • 0 is falsy
    • Applies for (u)int, (u)short, (ulong)
    • All other numbers are truthy
  • 0f and 0.0 are falsy
    • Any other floating point number is truthy, even float.nan and float.infinity!
  • The character literal '\0' is falsy

Array thuthiness

But what about static/dynamic arrays?
To test, let’s use the following template function:

Static arrays

Static arrays cannot be converted to booleans.

Dynamic arrays
  • string literals are truthy, whereas the null string and a string which is an empty array ([]) are falsy.
  • A non-empty array like [1, 2, 3] is truthy. An empty array is falsy.

In the last example, however, even though t‘s length was set to 0, it was truthy! But why?

To understand why, remember that a dynamic array can be thought as:

What the if-statement does it to check whether ptr is null. If it is not null, the expression is truthy, otherwise it’s falsy. It does not care about the length property!
So what happened is that the array’s length was set to 0, but its ptr property was not null. That is the reason the expression was truthy.

Because of this, you must not do

to test whether an array is empty or not, but check its length property.

Things to remember

  • D’s if-statement works more like C/C++’s instead of Java/C#’s
  • 0, 0.0f, 0.0 are falsy
  • nan and infinities are truthy
  • string literals are always truthy
  • Dynamic arrays whose ptr property is null are falsy. Otherwise they are truthy
  • Use the .length property of dynamic arrays to test whether they are empty or not