If Else in D Programming Language

Branching with if and else in D is straightforward.

import std.stdio;

void main() {
    // Here's a basic example.
    if (7 % 2 == 0) {
        writeln("7 is even");
    } else {
        writeln("7 is odd");
    }

    // You can have an `if` statement without an else.
    if (8 % 4 == 0) {
        writeln("8 is divisible by 4");
    }

    // Logical operators like `&&` and `||` are often
    // useful in conditions.
    if (8 % 2 == 0 || 7 % 2 == 0) {
        writeln("either 8 or 7 are even");
    }

    // A statement can precede conditionals; any variables
    // declared in this statement are available in the current
    // and all subsequent branches.
    if (auto num = 9; num < 0) {
        writeln(num, " is negative");
    } else if (num < 10) {
        writeln(num, " has 1 digit");
    } else {
        writeln(num, " has multiple digits");
    }
}

To run the program:

$ dmd -run if_else.d
7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digit

Note that you don’t need parentheses around conditions in D, but the braces are required.

D does not have a ternary if operator, so you’ll need to use a full if statement even for basic conditions. However, D provides an alternative in the form of the ?: operator, which can be used for simple conditional expressions.