Note: This website is archived. For up-to-date information about D projects and development, please visit wiki.dlang.org.

The switch-case Construct

Part of SwitchCaseCategory

Overview

The switch-case construct can be a good way to replace a complicated series of if/else if/else if/else.

How is switch-case useful?

Let's say you write a program that has a menu with a bunch of mutually exclusive options.

+---------+------+-------+------+
| File    | Edit | Tools | Help |
+---------+------+-------+------+
| New     |
| Open    |
| Save    |
| Print   |
|---------+
| Exit    |
+---------+

This is just the kind of situation that lead to the creation of the switch-case construct: only one of these options can be clicked at any given time. You can't click "Open" and "Exit" at the same time. So let's just go down the list. Maybe "New" was clicked, so run subroutine NewWasClicked(). If "Open" was clicked, then run subroutine OpenWasClicked(). And so on down list. If "Exit" was clicked then just PostQuitMessage(0). Finally the default case is there so that you can catch whatever might fall through the cracks.

Don't fall through (unless you want to)

D follows in the C/C++ tradition of "falling through" from the matched case to the cases below if there isn't a break statement. So unless you actually want all the code for the lower cases executed when the upper case is found, don't forget to include those breaks.

Example in the D Programming Language

int main()
{
    int i;

    switch(i)
    {
        case 0: 

            printf("i is zero"); 
            break;  
            /* Without each "break", 
               the flow will fall-through. */

        case 1: 
            printf("i is one");  
            break;

        case 2:
            printf("i is one");  
            break;
    
        default: 
            printf("i is one");  
            break;
    }
    return 0;
}

Equivalent example in QuickBASIC

Dim i%

Select Case i%
   Case 0: Print "i is zero"
   Case 1: Print "i is one"
   Case 2: Print "i is two"
   Case 3: Print "i is three"
   Case Else: Print "i is something else"
End Select

Output

i is zero

Automatic Initialization

By the way, did you notice that i is never explicitly assigned a value? Since D uses "automatic initialization", the integer i is automatically assigned a default value of 0 as it is declared without specifying another value.

Source

Link http://jcc_7.tripod.com/d/tutor/switch_case.html
Author jcc7