What are switch expressions in D?

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;
}

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;
}
}
}

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.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved