{"id":2041,"date":"2024-01-24T07:04:15","date_gmt":"2024-01-24T07:04:15","guid":{"rendered":"https:\/\/www.skillvertex.com\/blog\/?p=2041"},"modified":"2024-01-24T07:04:15","modified_gmt":"2024-01-24T07:04:15","slug":"switch-statement-in-c","status":"publish","type":"post","link":"https:\/\/www.skillvertex.com\/blog\/switch-statement-in-c\/","title":{"rendered":"Switch Statement in C"},"content":{"rendered":"\n<div class=\"wp-block-rank-math-toc-block\" id=\"rank-math-toc\" id=\"rank-math-toc\"><p>Table of Contents<\/p><nav><ul><li ><a href=\"#switch-statement-in-c\">Switch Statement in C<\/a><\/li><li ><a href=\"#what-is-switch-statement\">What is Switch Statement <\/a><\/li><li ><a href=\"#syntax-of-switch-statement\">Syntax Of Switch Statement <\/a><\/li><li ><a href=\"#how-to-use-switch-case-statements-in-c\">How to use switch case statements in C?<\/a><\/li><li ><a href=\"#rules-of-the-switch-case-statement\">Rules of the switch case statement<\/a><\/li><li ><a href=\"#how-does-switch-statement-work\">How Does Switch Statement Work?<\/a><\/li><li ><a href=\"#break-in-switch-case\">Break in switch case<\/a><\/li><li ><a href=\"#default-in-switch-case\">Default in Switch Case<\/a><\/li><li ><a href=\"#important-points-about-switch-case-statements\">Important Points About Switch Case Statements<\/a><\/li><li ><a href=\"#examples-of-switch-statement-in-c\">Examples of switch Statement in C<\/a><\/li><li ><a href=\"#advantages-of-c-switch-statement\">Advantages of C switch Statement<\/a><\/li><li ><a href=\"#disadvantages-of-c-switch-statement\">Disadvantages Of C Switch Statement <\/a><\/li><li ><a href=\"#faq-switch-statement-in-c\">FAQ- Switch Statement in C<\/a><\/li><\/ul><\/nav><\/div>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"switch-statement-in-c\">Switch Statement in C<\/h2>\n\n\n\n<p>The switch statement in C is a useful tool for making decisions in your code based on a specific value or variable. It&#8217;s like a roadmap that helps your program choose the right path to follow. Unlike long lists of if-else statements, the switch statement keeps things organized and efficient. In this guide, we&#8217;ll break down how the switch statement works in C, how to use it, and where it can come in handy to make your code more straightforward and easier to read. Whether you&#8217;re just starting to code or have some experience, the switch statement is a valuable tool to have in your C programming toolkit.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"what-is-switch-statement\">What is Switch Statement <\/h2>\n\n\n\n<p>A switch case statement in programming evaluates an expression and then, depending on the result (if it matches specific conditions), carries out certain actions. In simple terms, it&#8217;s like a tool to do different things based on different situations.<\/p>\n\n\n\n<p>Switch case statements help with making choices in your code. They&#8217;re an alternative to using long if statements to check if a variable matches specific values. Think of them as a way to direct your program&#8217;s flow in various directions.<\/p>\n\n\n\n<p>In technical terms, the switch statement is like a road with multiple branches. It directs your program to different sections of code based on the expression&#8217;s value. This makes it easier to handle various scenarios and keep your code organized.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"syntax-of-switch-statement\">Syntax Of Switch Statement <\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>switch(expression)\n{\ncase value1: statement_1;\n             break;\ncase value2: statement_2;\n             break;\n.\n.\n.\ncase value_n: statement_n;\n              break;\n\ndefault: default_statement;\n}<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"how-to-use-switch-case-statements-in-c\">How to use switch case statements in C?<\/h2>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"rules-of-the-switch-case-statement\">Rules of the switch case statement<\/h2>\n\n\n\n<p>In a switch statement:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>The &#8220;case value&#8221; can be of &#8220;char&#8221; and &#8220;int&#8221; type, meaning you can compare the switch expression to characters or integers.<\/li>\n\n\n\n<li>You can have one or multiple cases, allowing you to define different actions for different values.<\/li>\n\n\n\n<li>The values in the cases must be unique, ensuring that each case is distinct and does not overlap with others.<\/li>\n\n\n\n<li>Each statement within a case can have a break statement, which is optional. The break statement is used to exit the switch statement after a case is executed, preventing the code from falling through to subsequent cases.<\/li>\n\n\n\n<li>The default statement is also optional. It serves as a catch-all case when none of the other cases match the switch expression&#8217;s value. If present, the code within the default case will be executed.<\/li>\n<\/ol>\n\n\n\n<p>Example<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ C program to Demonstrate returning of day based numeric\n\/\/ value\n#include &lt;stdio.h&gt;\n \nint main()\n{\n  \/\/ switch variable\n    int var = 1;\n \n  \/\/ switch statement\n    switch (var) {\n        case 1:\n            printf(\"Case 1 is Matched.\");\n            break;\n \n        case 2:\n            printf(\"Case 2 is Matched.\");\n            break;\n \n        case 3:\n            printf(\"Case 3 is Matched.\");\n            break;\n \n        default:\n            printf(\"Default case is Matched.\");\n            break;\n    }\n \n    return 0;\n}<\/code><\/pre>\n\n\n\n<p>Output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Case 1 is Matched.\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"how-does-switch-statement-work\">How Does Switch Statement Work?<\/h2>\n\n\n\n<ol class=\"wp-block-list\">\n<li>First, the switch variable is evaluated.<\/li>\n\n\n\n<li>Then, the evaluated value is compared to all the cases present in the switch statement.<\/li>\n\n\n\n<li>If a matching case is found:\n<ul class=\"wp-block-list\">\n<li>The code associated with that case is executed.<\/li>\n\n\n\n<li>If there&#8217;s a &#8220;break&#8221; keyword in the case, the program exits the switch statement.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li>If no matching case is found, and there&#8217;s a &#8220;default&#8221; case:\n<ul class=\"wp-block-list\">\n<li>The code in the &#8220;default&#8221; case is executed.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li>If there&#8217;s no &#8220;break&#8221; keyword, all subsequent cases after the matching one will be executed.<\/li>\n\n\n\n<li>Finally, statements after the switch statement are executed.<\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"break-in-switch-case\">Break in switch case<\/h2>\n\n\n\n<p>The &#8220;break&#8221; keyword is used to halt the execution inside a switch block. It&#8217;s like an emergency exit that allows you to break out of the switchblock. When a &#8220;break&#8221; statement is encountered, the switch statement terminates, and the program continues to the next line after the switch block.<\/p>\n\n\n\n<p>The &#8220;break&#8221; statement is not mandatory. If you don&#8217;t use it, the program will keep executing the code in subsequent cases, even if they don&#8217;t match the initial condition. This behavior is known as &#8220;fall-through.&#8221;<\/p>\n\n\n\n<p>Example<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ C Program to demonstrate the behaviour of switch case\n\/\/ without break\n#include &lt;stdio.h&gt;\n \nint main()\n{\n \n    int var = 2;\n \n    \/\/ switch case without break\n    switch (var) {\n      case 1:\n          printf(\"Case 1 is executed.\\n\");\n      case 2:\n          printf(\"Case 2 is executed.\\n\");\n      case 3:\n          printf(\"Case 3 is executed.\");\n      case 4:\n          printf(\"Case 4 is executed.\");\n    }\n    return 0;\n}<\/code><\/pre>\n\n\n\n<p>Output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Case 2 is executed.\nCase 3 is executed.Case 4 is executed.<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"default-in-switch-case\">Default in Switch Case<\/h2>\n\n\n\n<p>The &#8220;default&#8221; keyword is used to define a set of statements that should execute when none of the case conditions match the switch variable.<\/p>\n\n\n\n<p>Using the &#8220;default&#8221; keyword is optional in a switch case statement. If you omit it and none of the cases match, the program will still run without any issues. It serves as a way to handle situations where none of the defined cases apply.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"important-points-about-switch-case-statements\">Important Points About Switch Case Statements<\/h2>\n\n\n\n<p><strong>1. Switch expression should result in a&nbsp;constant value<\/strong><\/p>\n\n\n\n<p>In C and C++, the expression in a switch statement must yield a constant value. Valid expressions include numeric constants, enumerations, and preprocessor macro constants. This constraint ensures that cases can be compared effectively.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Constant expressions allowed\nswitch(1+2+23)\nswitch(1*2+3%4)\n\n\/\/ Variable expression are allowed provided\n\/\/ they are assigned with fixed values\nswitch(a*b+c*d)\nswitch(a+b+c)<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">2. Expression value should be only of int or char type.<\/h4>\n\n\n\n<p>The switch statement in C\/C++ can only evaluate expressions that return values of type int or char, limiting the types of expressions it can handle.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">3. Case Values must be Unique<\/h4>\n\n\n\n<p>In C, the switch statement does not allow duplicate case values. Each case label must be unique within the same switch block. This ensures that the program can accurately determine which code block to execute based on the switch expression&#8217;s value.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">4. Nesting of switch Statements<\/h4>\n\n\n\n<p>Nesting of switch statements is allowed in C\/C++, meaning you can have switch statements inside another switch. However, it&#8217;s generally recommended to avoid excessive nesting because it can make the program more complex and harder to read and maintain. It&#8217;s often a better practice to refactor the code to make it more understandable and modular when you find the need for nested switch statements.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"examples-of-switch-statement-in-c\">Examples of switch Statement in C<\/h2>\n\n\n\n<h4 class=\"wp-block-heading\">Example 1: &nbsp;C Program to print the day of the week using a switch case<\/h4>\n\n\n\n<pre class=\"wp-block-code\"><code>\n\/\/ C program to print the day using switch\n#include &lt;stdio.h&gt;\n \n\/\/ Driver Code\nint main()\n{\n    int day = 2;\n \n    printf(\"The day with number %d is \", day);\n    switch (day) {\n      case 1:\n          printf(\"Monday\");\n          break;\n      case 2:\n          printf(\"Tuesday\");\n          break;\n      case 3:\n          printf(\"Wednesday\");\n          break;\n      case 4:\n          printf(\"Thursday\");\n          break;\n      case 5:\n          printf(\"Thursday\");\n          break;\n      case 6:\n          printf(\"Thursday\");\n          break;\n      case 7:\n          printf(\"Thursday\");\n          break;\n      default:\n          printf(\"Invalid Input\");\n          break;\n      }\n return 0;\n}<\/code><\/pre>\n\n\n\n<p>Output <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>The day with number 2 is Tuesday\n<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"example-2-simple-calculator-using-switch-case-in-c\">Example 2: Simple Calculator using switch case in C<\/h4>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ C Program to create a simple calculator using switch\n\/\/ statement\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n \n\/\/ driver code\nint main()\n{\n    \/\/ switch variable\n    char choice;\n    \/\/ operands\n    int x, y;\n \n    while (1) {\n        printf(\"Enter the Operator (+,-,*,\/)\\nEnter x to \"\n               \"exit\\n\");\n        scanf(\" %c\", &amp;choice);\n \n        \/\/ for exit\n        if (choice == 'x') {\n            exit(0);\n        }\n \n        printf(\"Enter the two numbers: \");\n        scanf(\"%d %d\", &amp;x, &amp;y);\n \n        \/\/ switch case with operation for each operator\n        switch (choice) {\n          case '+':\n              printf(\"%d + %d = %d\\n\", x, y, x + y);\n              break;\n\n          case '-':\n              printf(\"%d - %d = %d\\n\", x, y, x - y);\n              break;\n \n          case '*':\n              printf(\"%d * %d = %d\\n\", x, y, x * y);\n              break;\n          case '\/':\n              printf(\"%d \/ %d = %d\\n\", x, y, x \/ y);\n              break;\n          default:\n              printf(\"Invalid Operator Input\\n\");\n        }\n    }\n    return 0;\n}<\/code><\/pre>\n\n\n\n<p>Output <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Enter the operator (+, -, *, \/)\n\nEnter x to exit\n\n+\nEnter the two numbers: 100 + 200\n100 + 200 = 300<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"advantages-of-c-switch-statement\">Advantages of C switch Statement<\/h2>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Easier to Read:<\/strong> Switch statements can be more readable than a long series of if-else if statements when dealing with multiple conditions. They provide a cleaner and more structured way to handle branching.<\/li>\n\n\n\n<li><strong>Easier to Debug and Maintain:<\/strong> Switch statements can be easier to debug and maintain, especially when there are many conditions to handle. The code is organized into distinct cases, making it simpler to locate and address issues.<\/li>\n\n\n\n<li><strong>Faster Execution Speed:<\/strong> In some cases, switch statements can lead to faster execution speeds compared to long chains of if-else if statements because the compiler can optimize them more efficiently.<\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"disadvantages-of-c-switch-statement\">Disadvantages Of C Switch Statement <\/h2>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Limited Data Types:<\/strong> Switch cases can only evaluate expressions of type int or char, which restricts the types of values that can be directly compared within the switch statement.<\/li>\n\n\n\n<li><strong>No Support for Logical Expressions:<\/strong> Unlike if-else statements, switch cases do not support logical expressions. You cannot directly compare complex conditions within a case, which may require additional logic or nesting.<\/li>\n\n\n\n<li><strong>Required &#8220;break&#8221; Statements:<\/strong> It&#8217;s essential to remember to include a &#8220;break&#8221; statement at the end of each case to prevent fall-through behavior. Forgetting to include &#8220;break&#8221; can lead to the unintended execution of subsequent cases.<\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"faq-switch-statement-in-c\">FAQ- Switch Statement in C<\/h2>\n\n\n<div id=\"rank-math-faq\" class=\"rank-math-block\">\n<div class=\"rank-math-list \">\n<div id=\"faq-question-1695296009333\" class=\"rank-math-list-item\">\n<h4 class=\"rank-math-question \">Q1. What is a switch statement with an example in C?<\/h4>\n<div class=\"rank-math-answer \">\n\n<p>Ans. The switch statement in C serves as an alternative to the if-else-if ladder statement. It enables the execution of various operations based on different possible values of a single variable, known as the switch variable. Within the switch statement, you can define distinct sets of statements for different values of the switch variable, making it a structured way to handle multiple cases or conditions.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1695296058562\" class=\"rank-math-list-item\">\n<h4 class=\"rank-math-question \">Q2. What is a switch statement in syntax?<\/h4>\n<div class=\"rank-math-answer \">\n\n<p>Ans. <br \/>The &#8220;case&#8221; keyword is followed by a constant expression, and it ends with a colon. This expression specifies the value to be matched with the switch expression.<br \/>If the value of the switch expression matches the constant expression in a case label, the statements following that case label (until a &#8220;break&#8221; statement or the end of the switch block) will be executed.<br \/>Typically, one or more statements follow a case label to define the actions to be taken when a particular case is matched.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1695296476095\" class=\"rank-math-list-item\">\n<h4 class=\"rank-math-question \">Q3. Is a switch statement a loop?<\/h4>\n<div class=\"rank-math-answer \">\n\n<p>Ans. A switch statement in C\/C++ is not a loop; it&#8217;s a conditional control structure used for making decisions based on the value of a switch expression. It&#8217;s often likened to an &#8220;if-else-if-else&#8221; type statement because it allows you to evaluate multiple conditions and execute different blocks of code based on the matching case. While loops are used for repetitive execution, switch statements are used for branching based on specific values.<\/p>\n\n<\/div>\n<\/div>\n<\/div>\n<\/div>","protected":false},"excerpt":{"rendered":"<p>Switch Statement in C The switch statement in C is a useful tool for making decisions in your code based on a specific value or variable. It&#8217;s like a roadmap that helps your program choose the right path to follow. Unlike long lists of if-else statements, the switch statement keeps things organized and efficient. In &#8230; <a title=\"Switch Statement in C\" class=\"read-more\" href=\"https:\/\/www.skillvertex.com\/blog\/switch-statement-in-c\/\" aria-label=\"More on Switch Statement in C\">Read more<\/a><\/p>\n","protected":false},"author":4,"featured_media":2042,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[27],"tags":[348],"class_list":["post-2041","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-c-programming","tag-switch-statement-in-c","generate-columns","tablet-grid-50","mobile-grid-100","grid-parent","grid-33"],"_links":{"self":[{"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/posts\/2041","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/users\/4"}],"replies":[{"embeddable":true,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/comments?post=2041"}],"version-history":[{"count":6,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/posts\/2041\/revisions"}],"predecessor-version":[{"id":6448,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/posts\/2041\/revisions\/6448"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/media\/2042"}],"wp:attachment":[{"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/media?parent=2041"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/categories?post=2041"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/tags?post=2041"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}