Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

switch
d

What are switch expressions in D?

Mohe Ud Din Sheikh

Overview

In D programming language, switch works similarly to the if statement, but its code is relatively clearer and easier to understand.

In the switch statement, there is a block of code against each value under comparison, known as a case. If the statement matches any case value, it executes that block of code. Otherwise, the default case code gets executed.

Syntax

Let's review the syntax for a better understanding.

 switch (c) {

        case 1:
           //This block will execute if the passed value is equal to 1
            break;

        case 2:
            //This block will execute if the passed value is equal to 2
            break;

        case 3:
           //This block will execute if the passed value is equal to 3
            break;

        default:
            //This block will execute if the passed value is not equal to any case
            break;
        }
Syntax of `switch` statement in the D language

We use switch expressions in which we pass the value that will be compared with the case value. If the value is matches with the case, that case block will be executed.

Example

Let's have a look at the following example.

import std.stdio;

void main() {
    // Passing values to c
    foreach (c ; [ 1, 2,3,20 ]) {
        // Passing the values of c to the switch statment
        switch (c) {
            // Declaring case 1 code block
            case 1:
                writeln("I am from case 1");
                break;
            // Declaring case 2 code block
            case 2:
                writeln("I am from case 2");
                break;
            // Declaring case 3 code block
            case 3:
                writeln("I am from case 3");
                break;
            // Declaring default code block
            default:
                writeln("I am from default case");
                break;
        }
    }
}
Program example of switch in the D language

Explanation

  • Line 7: We use switch expressions in which we pass the values that will be compared with the case value.
  • Lines 9–24: We declare different cases. Either the matched case or the default case code block will be executed.

RELATED TAGS

switch
d

CONTRIBUTOR

Mohe Ud Din Sheikh
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring