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 1break;case 2://This block will execute if the passed value is equal to 2break;case 3://This block will execute if the passed value is equal to 3break;default://This block will execute if the passed value is not equal to any casebreak;}
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 cforeach (c ; [ 1, 2,3,20 ]) {// Passing the values of c to the switch statmentswitch (c) {// Declaring case 1 code blockcase 1:writeln("I am from case 1");break;// Declaring case 2 code blockcase 2:writeln("I am from case 2");break;// Declaring case 3 code blockcase 3:writeln("I am from case 3");break;// Declaring default code blockdefault:writeln("I am from default case");break;}}}
Explanation
- Line 7: We use
switchexpressions in which we pass the values that will be compared with thecasevalue. - Lines 9–24: We declare different cases. Either the matched
caseor thedefaultcase code block will be executed.
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved