switch-statement-in-c++

“`html

The switch statement in C++ serves as a robust control flow mechanism that streamlines decision-making in programming. It carries out various code segments depending on the value of a singular expression. This structure is a proficient substitute for if-else if sequences, whether for crafting a basic calculator or easily deciding based on user input. In this article, we will explore what a switch statement is in C++, its syntax, operation, flowchart, rules, examples, benefits and drawbacks, as well as the distinctions between a switch statement and an if-else if structure in C++.

Table of Contents:

What is a switch Statement in C++?

The switch statement in C++ functions as a control flow mechanism that executes various code segments based on the value of a singular expression. Typically, the expression’s value is an integer or an enum. It acts as a replacement for multiple if-else statements when the same variable is evaluated against various constant values. This structure is composed of three keywords: switch, case, and default.

Example:

Cpp

Code Copied!

var isMobile = window.innerWidth “);

editor61766.setValue(decodedContent); editor61766.clearSelection();

editor61766.setOptions({ maxLines: Infinity });

function decodeHTML61766(input) { var doc = new DOMParser().parseFromString(input, “text/html”); return doc.documentElement.textContent; }

// Function to copy code to clipboard function copyCodeToClipboard61766() { const code = editor61766.getValue(); navigator.clipboard.writeText(code).then(() => { jQuery(“.maineditor61766 .copymessage”).show(); setTimeout(function() { jQuery(“.maineditor61766 .copymessage”).hide(); }, 2000); }).catch(err => { console.error(“Error copying code: “, err); }); }

function runCode61766() {

var code = editor61766.getSession().getValue();

jQuery(“#runBtn61766 i.run-code”).show(); jQuery(“.output-tab”).click();

jQuery.ajax({ url: “https://intellipaat.com/blog/wp-admin/admin-ajax.php”, type: “post”, data: { language: “cpp”, code: code, cmd_line_args: “”, variablenames: “”, action:”compilerajax” }, success: function(response) { var myArray = response.split(“~”); var data = myArray[1];

jQuery(“.output61766”).html(“

"+data+"");
            jQuery(".maineditor61766 .code-editor-output").show();
            jQuery("#runBtn61766 i.run-code").hide();
        }
    });
}

function closeoutput61766() {
    var code = editor61766.getSession().getValue();
    jQuery(".maineditor61766 .code-editor-output").hide();
}

// Attach event listeners to the buttons
document.getElementById("copyBtn61766").addEventListener("click", copyCodeToClipboard61766);
document.getElementById("runBtn61766").addEventListener("click", runCode61766);
document.getElementById("closeoutputBtn61766").addEventListener("click", closeoutput61766);


Output:

switch Statement in C++ Example

This code demonstrates how a switch statement can be utilized to display the name of the day based on the integer representation of the day. Since the value is 3, it outputs “Wednesday” accordingly.

``````html

Structure of switch Statement in C++

The typical structure of the switch statement in C++ is presented below:

switch (expression) {
case constant1:
// Code to execute if expression == constant1
break;
case constant2:
// Code to execute if expression == constant2
break;
// Additional cases as required
default:
// Code to execute if no case matches
}

In this context,

  • expression: This represents a value or variable that undergoes evaluation.
  • case constant1: A potential value of the expression; if the expression matches constant1, the associated code block will be executed.
  • break: This keyword concludes the switch statement and prevents proceeding to the subsequent case.
  • default: An optional case that executes when none of the other cases correspond.

Terms in switch Statement in C++

There are three key terms within the switch statement in C++:

1. switch

  • Initiates the switch statement and evaluates an expression.
  • Example: switch (value)

2. case

  • Specifies the individual constant values for comparison with the switch expression.
  • Every case executes the code within its block.
  • Example: case 1:

3. default

  • This optional keyword executes when no alternative case matches.
  • It functions like an else statement in an if-else structure.
  • Example: default:

Flowchart of switch Statement in C++

Flowchart of Switch Statement in C++

Functioning of switch Statement in C++

Below is an outlined process of the functioning of the switch statement in C++:

Step 1: Evaluate the expression

The switch expression undergoes evaluation a single time.

Step 2: Compare values with cases

The expression’s value is compared to each of the cases.

  • If a match happens, the code for that case is executed.
  • If no match is found, the default case is examined.

Step 3: Exit via break

  • If a break is absent, the following case executes.

Step 4: Default Case

If there is no match among the cases, the code under the default case executes.

Guidelines for switch Statement in C++

The following guidelines must be adhered to when using the switch statement in C++:

  1. The switch statement exclusively supports integral types like int, char, and enum.
  2. An unlimited number of cases can be utilized in the switch statement.
  3. A case label must be a constant rather than a variable.
  4. Each case label within the switch block must be distinct.
  5. The break statement is optional; however, every case statement may include a break.
  6. Each case block possesses its own scope.

Illustrations of switch Statement in C++

Presented below are several examples of switch statements in C++:

Example 1: Basic Calculator utilizing the switch

Cpp

Code Copied!

var isMobile = window.innerWidth “);

editor64653.setValue(decodedContent); editor64653.clearSelection();

editor64653.setOptions({ maxLines: Infinity });

function decodeHTML64653(input) { var doc = new DOMParser().parseFromString(input, “text/html”); return doc.documentElement.textContent; }

// Function to copy code to clipboard function copyCodeToClipboard64653() { const code = editor64653.getValue(); navigator.clipboard.writeText(code).then(() => { jQuery(“.maineditor64653 .copymessage”).show(); setTimeout(function() { jQuery(“.maineditor64653 .copymessage”).hide(); }, 2000); }).catch(err => { console.error(“Error copying code: “, err); }); }

function runCode64653() { var code = editor64653.getSession().getValue();

jQuery(“#runBtn64653 i.run-code”).show(); jQuery(“.output-tab”).click();

jQuery.ajax({ url: “https://intellipaat.com/blog/wp-admin/admin-ajax.php”, type: “post”, data: { language: “cpp”, code: “““html code, cmd_line_args: “”, variablenames: “”, action:”compilerajax” }, success: function(response) { var myArray = response.split(“~”); var data = myArray[1];

jQuery(“.output64653”).html(“

"+data+"");
    jQuery(".maineditor64653 .code-editor-output").show();
    jQuery("#runBtn64653 i.run-code").hide();
}

})

}

function closeoutput64653() { var code = editor64653.getSession().getValue(); jQuery(".maineditor64653 .code-editor-output").hide(); }

// Attach event handlers to the buttons document.getElementById("copyBtn64653").addEventListener("click", copyCodeToClipboard64653); document.getElementById("runBtn64653").addEventListener("click", runCode64653); document.getElementById("closeoutputBtn64653").addEventListener("click", closeoutput64653);

Output:

Example 1: Simple Calculator using the switch

The code illustrates how a basic calculator can be constructed utilizing the switch statement to execute fundamental arithmetic functions such as addition, subtraction, multiplication, and division. In this calculator, you must first enter one number, followed by an operator for the operation, and then another number, after which the result will be displayed. Given that the initial number is 10, the operator is * for multiplication, and the second number is 20, the resulting output is 200.

Example 2: Displaying Messages Based on a Grade Without Using Break

Cpp

Code Copied!

var isMobile = window.innerWidth ");

editor69448.setValue(decodedContent); // Set the default text editor69448.clearSelection();

editor69448.setOptions({ maxLines: Infinity });

function decodeHTML69448(input) { var doc = new DOMParser().parseFromString(input, "text/html"); return doc.documentElement.textContent; }

// Function to copy code to clipboard function copyCodeToClipboard69448() { const code = editor69448.getValue(); // Get code from the editor navigator.clipboard.writeText(code).then(() => { // alert("Code copied to clipboard!"); jQuery(".maineditor69448 .copymessage").show(); setTimeout(function() { jQuery(".maineditor69448 .copymessage").hide(); }, 2000); }).catch(err => { console.error("Error copying code: ", err); }); }

function runCode69448() { var code = editor69448.getSession().getValue();

jQuery("#runBtn69448 i.run-code").show(); jQuery(".output-tab").click();

jQuery.ajax({ url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php", type: "post",

data: { language: "cpp", code: code, cmd_line_args: "", variablenames: "", action:"compilerajax" }, success: function(response) { var myArray = response.split("~"); var data = myArray[1];

jQuery(".output69448").html("

"+data+"");
            jQuery(".maineditor69448 .code-editor-output").show();
            jQuery("#runBtn69448 i.run-code").hide();
        }
    })
}

function closeoutput69448() { var code = editor69448.getSession().getValue(); jQuery(".maineditor69448 .code-editor-output").hide(); }

// Attach event listeners to the buttons document.getElementById("copyBtn69448").addEventListener("click", copyCodeToClipboard69448); document.getElementById("runBtn69448").addEventListener("click", runCode69448); document.getElementById("closeoutputBtn69448").addEventListener("click", closeoutput69448);

Output:

Example 2: Printing Messages based on a Grade without Using break

The code demonstrates how a switch statement is employed to classify a student’s grade, and due to the absence of a break, multiple messages are printed corresponding to the grade achieved by the student. In this scenario, with a grade of B, the output is “Well done! Good job! You passed! Better luck next time!”.

Example 3: Utilizing switch with Enum for the Days of the Week

Cpp

Code Copied!
``````html

var isMobile = window.innerWidth "");

editor48832.setValue(decodedContent); // Set the default text editor48832.clearSelection();

editor48832.setOptions({ maxLines: Infinity });

function decodeHTML48832(input) { var doc = new DOMParser().parseFromString(input, "text/html"); return doc.documentElement.textContent; }

// Function to duplicate code to clipboard function copyCodeToClipboard48832() { const code = editor48832.getValue(); // Acquire code from the editor navigator.clipboard.writeText(code).then(() => { // alert("Code duplicated to clipboard!");

jQuery(".maineditor48832 .copymessage").show(); setTimeout(function() { jQuery(".maineditor48832 .copymessage").hide(); }, 2000); }).catch(err => { console.error("Issue duplicating code: ", err); }); }

function runCode48832() { var code = editor48832.getSession().getValue();

jQuery("#runBtn48832 i.run-code").show(); jQuery(".output-tab").click();

jQuery.ajax({ url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php", type: "post",

data: { language: "cpp", code: code, cmd_line_args: "", variablenames: "", action:"compilerajax" }, success: function(response) { var myArray = response.split("~"); var data = myArray[1];

jQuery(".output48832").html("

"+data+"");
            jQuery(".maineditor48832 .code-editor-output").show();
            jQuery("#runBtn48832 i.run-code").hide();
        }
    });
}

function closeoutput48832() { var code = editor48832.getSession().getValue(); jQuery(".maineditor48832 .code-editor-output").hide(); }

// Bind event listeners to the buttons document.getElementById("copyBtn48832").addEventListener("click", copyCodeToClipboard48832); document.getElementById("runBtn48832").addEventListener("click", runCode48832); document.getElementById("closeoutputBtn48832").addEventListener("click", closeoutput48832);

Result:

Example 3: Using switch with enum for Day of the Week

The sample illustrates how the switch statement is employed with an enum to output messages corresponding to the day of the week, indicating whether it's the start, middle, or end of the week. Here, today is predefined as Wednesday, consequently, the output “Midweek!” is logged to the console.

Example 4: Switch with Default Case

Cpp

Code Duplicated!

var isMobile = window.innerWidth "");

editor63098.setValue(decodedContent); // Set the default text editor63098.clearSelection();

editor63098.setOptions({ maxLines: Infinity });

function decodeHTML63098(input) { var doc = new DOMParser().parseFromString(input, "text/html"); return doc.documentElement.textContent; }

// Function to duplicate code to clipboard function copyCodeToClipboard63098() { const code = editor63098.getValue(); // Obtain code from the editor navigator.clipboard.writeText(code).then(() => { // alert("Code duplicated to clipboard!");

jQuery(".maineditor63098 .copymessage").show(); setTimeout(function() { jQuery(".maineditor63098 .copymessage").hide(); }, 2000); }).catch(err => { console.error("Issue duplicating code: ", err); }); }

function runCode63098() { var code = editor63098.getSession().getValue();

jQuery("#runBtn63098 i.run-code").show(); jQuery(".output-tab").click();

jQuery.ajax({ url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php", type: "post",

data: { language: "cpp", code: code, cmd_line_args: "", variablenames: "", action:"compilerajax" }, success: function(response) { // remaining code } }); } ``````javascript { var myArray = response.split(""~""); var data = myArray[1];

jQuery("".output63098"").html("<pre>" + data + "</pre>"); jQuery("".maineditor63098 .code-editor-output"").show(); jQuery(""#runBtn63098 i.run-code"").hide(); }

function closeoutput63098() { var code = editor63098.getSession().getValue(); jQuery("".maineditor63098 .code-editor-output"").hide(); }

// Bind event listeners to the buttons document.getElementById(""copyBtn63098"").addEventListener(""click"", copyCodeToClipboard63098); document.getElementById(""runBtn63098"").addEventListener(""click"", runCode63098); document.getElementById(""closeoutputBtn63098"").addEventListener(""click"", closeoutput63098);

Result:

Example 4: Switch with Default Case

The snippet illustrates how a switch statement with a default case is employed to verify if the input number corresponds to any of the cases. In this instance, the number provided is 5, leading to the output “Invalid number! Please enter a number between 1 and 3” being logged to the console.

Example 5: Classifying Months Using switch Statement

Cpp

Code Duplicated!

var isMobile = window.innerWidth { jQuery("".maineditor8794 .copymessage"").show(); setTimeout(function() { jQuery("".maineditor8794 .copymessage"").hide(); }, 2000); }).catch(err => { console.error(""Error duplicating code:", err); }); }

function runCode8794() { var code = editor8794.getSession().getValue();

jQuery(""#runBtn8794 i.run-code"").show(); jQuery("".output-tab"").click();

jQuery.ajax({ url: ""https://intellipaat.com/blog/wp-admin/admin-ajax.php"", type: ""post"", data: { language: ""cpp"", code: code, cmd_line_args: """", variablenames: """", action: ""compilerajax"" }, success: function(response) { var myArray = response.split(""~""); var data = myArray[1];

jQuery("".output8794"").html("<pre>" + data + "</pre>"); jQuery("".maineditor8794 .code-editor-output"").show(); jQuery(""#runBtn8794 i.run-code"").hide(); } }); }

function closeoutput8794() { var code = editor8794.getSession().getValue(); jQuery("".maineditor8794 .code-editor-output"").hide(); }

// Bind event listeners to the buttons document.getElementById(""copyBtn8794"").addEventListener(""click"", copyCodeToClipboard8794); document.getElementById(""runBtn8794"").addEventListener(""click"", runCode8794); document.getElementById(""closeoutputBtn8794"").addEventListener(""click"", closeoutput8794);

Result:

Example 5: Categorizing Months Using Switch Statement

The snippet demonstrates how a switch statement categorizes months into their relevant seasons. Given that the month is 10, the output “Autumn” is logged to the console.

Distinction between switch and if-else if structure in C++

``````html

Aspect switch if-else if structure
Type of Expression Operates with constant values (e.g., int, char, enum) Can manage any expression (e.g., relational, logical)
Efficiency Typically quicker for numerous cases Slower for extensive conditions
Intricate Conditions Cannot assess ranges or complicated expressions Can manage intricate conditions
Transitioning to Another Case Permits transitioning when a break is absent No transition and halts at the initial true condition
Default Management Can utilize a default case (optional) Demands an else block for unmatched conditions
Application Scenarios Optimal for contrasting a variable with constant values Appropriate for more intricate or dynamic conditions
Restrictions Constrained to constant value comparisons No restrictions on condition complexity
Notation switch(expression) { case: &hellip; } if(condition) { &hellip; } else if { &hellip; }

Benefits of switch Statement in C++

  1. It offers a tidy and structured approach to manage multiple constant conditions effectively.
  2. The switch statement is typically more efficient than if-else due to compiler enhancements.
  3. It reduces the necessity of using if-else if, simplifying the code and enhancing clarity.
  4. The switch statement includes a default case to easily identify unmatched values.
  5. Modifying cases becomes simpler when working with numerous fixed values.
  6. The format of the switch statement is straightforward and comprehensible.

Drawbacks of switch Statement in C++

  1. It solely accommodates integral values such as int, char, or enum, and does not include float, double, or string.
  2. Logical or relational expressions are not permissible in the case labels.
  3. Omitting the break might lead to unintentional execution of the next case, potentially causing bugs.
  4. The switch statement lacks flexibility when conditions are based on ranges or multiple variables.
  5. Cases cannot be combined using expressions like those found in if-else.

Final Thoughts

The switch statement in C++ is a crucial control structure that simplifies the handling of multiple constant values. It features clear syntax and demonstrates better performance compared to an if-else if statement. Nevertheless, it has specific rules, benefits, and drawbacks. By comprehending how a switch statement functions, the regulations to adhere to, and its advantages and disadvantages, you can effectively write a C++ program utilizing the switch statement.

Switch Statement in C++ &ndash; FAQs

Q1. Can switch operate with strings?

No, a switch statement exclusively supports int, char, and enum.

Q2. What happens if I omit a break in a case?

If you omit a break in a case, the subsequent case will also execute.

Q3. Is the default case mandatory?

No, it is not mandatory. It is optional, but utilizing the default case for unmatched cases is advisable.

Q4. Can two cases utilize the same code?

Yes, you only have to stack them without a break in between.

Q5. Is switch faster than if-else?

Yes, switch is faster than if-else with numerous constant cases.

The post Switch Statement in C++ appeared first on Intellipaat Blog.

```


Leave a Reply

Your email address will not be published. Required fields are marked *

Share This