Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 36 ยท Control Flow and Functions

Conditionals in D: if, else, switch and final switch

Make decisions in D with if and else, the ternary operator, switch with strings and case ranges, final switch over enums, and static if for compile-time conditions.

Control flow decides which code runs. D's conditionals look like C's, with a few improvements that prevent classic bugs: switch can match strings and ranges, it does not silently fall through from one case to the next by accident, and final switch makes the compiler check that you handled every enum member. This lesson covers if, switch, final switch, and the compile-time static if. D listings are read-only; C stand-ins model the same decisions.

if, else if, else

D
import std.stdio;

void main()
{
    int score = 73;
    if (score >= 90)
    {
        writeln("A");
    }
    else if (score >= 70)
    {
        writeln("B");
    }
    else
    {
        writeln("C or lower");
    }
}

This prints B. The condition must be an expression convertible to bool. Braces are optional for a single statement, but always using them avoids the "dangling else" and the bug of adding a second line that is not actually inside the if.

A neat D feature is declaring a variable in the condition, scoped to the if:

D
if (auto p = "key" in settings)
{
    writeln("found ", *p);
}
else
{
    writeln("missing");
}

switch

switch compares one value against several constants. In D the value may be an integer, a character, an enum, or a string:

D
import std.stdio;

void describe(string cmd)
{
    switch (cmd)
    {
        case "start":
            writeln("Starting");
            break;
        case "stop":
        case "halt":                 // two labels, one body
            writeln("Stopping");
            break;
        default:
            writeln("Unknown: ", cmd);
            break;
    }
}

Rules worth remembering:

  • A default: is required in an ordinary switch (the compiler errors without it, or without a case for every possibility).
  • A non-empty case body must end with break, return, goto case, continue or a thrown exception. Falling into the next case by accident is an error. If you really want it, write goto case;.
  • Several labels in a row share one body, as with "stop" and "halt" above.

D also has case ranges, which save long lists:

D
switch (ch)
{
    case 'a': .. case 'z':
        writeln("lowercase");
        break;
    case '0': .. case '9':
        writeln("digit");
        break;
    default:
        writeln("other");
}

The range is inclusive on both ends, unlike the half-open ranges in foreach.

final switch

With an enum, final switch forces you to cover every member and forbids default. If you later add a member, every final switch that misses it stops compiling:

D
enum Light { red, yellow, green }

string action(Light l)
{
    final switch (l)
    {
        case Light.red:    return "stop";
        case Light.yellow: return "slow down";
        case Light.green:  return "go";
    }
}

action(Light.green) returns "go". This is one of the best habits in D: it turns "I forgot a case" into a compile error rather than a run-time surprise.

static if

static if decides at compile time and does not create a new scope, so declarations inside stay visible. It is the foundation of templates and conditional compilation:

D
version (Windows)
{
    enum pathSeparator = '\\';
}
else
{
    enum pathSeparator = '/';
}

static if (size_t.sizeof == 8)
{
    enum bits = 64;
}
else
{
    enum bits = 32;
}

Code in the false branch is not even compiled, so it may refer to things that do not exist on this platform. version (...) handles platform and feature flags such as Windows, linux, X86_64 and unittest.

C stand-ins for decisions

C C stand-in: if/else chain with grading

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The output is 95 -> A, 73 -> B, 40 -> C or lower.

C C stand-in: switch with case ranges (a GCC extension)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

It prints lowercase, uppercase, digit and other for the four characters. Case ranges are not standard C; they are a GCC extension, but D supports them as part of the language.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What must every non-empty case body in a D switch end with?

    D rejects accidental fallthrough.
  2. 2. What is special about final switch?

    The compiler checks that all members are covered.
  3. 3. Which statement decides at compile time and creates no scope?

    static if is resolved by the compiler; unused branches are not compiled.
  4. 4. Is the range in case 'a': .. case 'z': inclusive?

    Case ranges include both bounds.

Summary

  • if/else take any boolean expression; you can declare a variable in the condition.
  • switch accepts strings and case ranges, forbids accidental fallthrough and requires default.
  • final switch over an enum guarantees every member is handled.
  • static if and version choose code at compile time.

Next: Loops and foreach