A Beginner's Guide to D/Conditions and Loops/Switch Statement


Basics

The switch statement can be found in almost every programming language, it's commonly used for checking multiple conditions. Syntax is identical as it is in C++ or Java. It has following form:

switch(variable)
{
        case value_to_check:
                statements;
                break;
 
        default:
                statements;
}

Here's some simple example:

import std.stdio,
        std.string : strip;
 
void main()
{
        // Command that user want to launch
        string input;
 
        write("Enter some command: ");
 
        // Get input without whitespaces, such as newline
        input = strip(readln());
 
        // We are checking input variable
        switch( input ) 
        {
                // If input is equals to '/hello'
                case "/hello":
                        writeln("Hello!");
                        break;
 
                // If it is equals to '/bye'
                case "/bye":
                        writeln("Bye!");
                        break;
 
                // None of specified, unknown command
                default:
                        writeln("I don't know that command");
        }
}

And the result of our code:

Enter some command: /hello
Hello!

Note break keyword after each case! If it's bypassed each case after it will be called. So here's console output of code without breaks:

Enter some command: /hello
Hello!
Bye!
I don't know that command

As you may see, all cases after /hello were "called", this is useful if we want to call same statements in more that one case. Here's one more example:

string cmd = "/hi";
 
switch( cmd )
{
        case "/hi":
        case "/hello":
        case "/wassup":
                writeln("Hi!");
                break;
 
        // ...
}
↑Jump back a section
Last modified on 13 September 2011, at 12:42