Although D does not provide support for if-then-else constructs, it does provide support for simple conditional expressions using the ?
and :
operators. These operators enable a triplet of expressions to be associated where the first expression is used to conditionally evaluate one of the other two. For example, the following D statement could be used to set a variable x
to one of two strings depending on the value of i
:
x = i == 0 ? "zero" : "non-zero";
In this example, the expression i == 0
is first evaluated to determine whether it is true or false. If the first expression is true, the second expression is evaluated and the ?:
expression returns its value. If the first expression is false, the third expression is evaluated and the ?:
expression return its value.
As with any D operator, you can use multiple ?:
operators in a single expression to create more complex expressions. For example, the following expression would take a char
variable c
containing one of the characters 0-9, a-z, or A-Z and return the value of this character when interpreted as a digit in a hexadecimal (base 16) integer:
hexval = (c >= '0' && c <= '9') ? c - '0' : (c >= 'a' && c <= 'z') ? c + 10 - 'a' : c + 10 - 'A';
The first expression used with ?:
must be a pointer or integer in order to be evaluated for its truth value. The second and third expressions may be of any compatible types. You may not construct a conditional expression where, for example, one path returns a string and another path returns an integer. The second and third expressions also may not invoke a tracing function such as trace
or printf
. If you want to conditionally trace data, use a predicate instead, as discussed in Chapter 1, Introduction.