Although D does not provide support for
if-then-else
constructs, it does provide
support for simple conditional expressions by 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 the previous example, the expression i ==
0
is first evaluated to determine whether it is true
or false. If the expression is true, the second expression is
evaluated and its value is returned. If the expression is false,
the third expression is evaluated and its value is returned.
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-f
, or
A-F
, 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 <= 'f') ? c + 10 - 'a' : c + 10 - 'A';
To be evaluated for its truth value, the first expression that
is used with ?:
must be a pointer or integer.
The second and third expressions can 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. See
Section 2.4, “Predicate Examples” for more information.