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