Posted December 8, 2012 by Victor in C/C++ Programming

How to Use Switch Statements in C++


Switch statements are used as a way of carrying out deep conditional statements. Such statement ensure that a given variable is tested for equality in relation to given values. Each of these values is referred to as a case and the variable being switched is checked against each case.

Perhaps you have used the if/else statements. However, when conditions have to be nested deeply, using the if/else statements can confuse individuals. It is for this reason that the switch statements are used to branch out on any number of values.

Here is how the switch syntax looks like:

Switch (expression)
    case (Constant Expression):

Rules Used In Switch Statement Syntax

There are several things to know about writing Switch statements and they are:

  1. There is no limit to the number of case statement that can be used within a given switch.
  2. Every case statement has the value in comparison and a colon.
  3. The cases within a switch statement should have a constant-expression which is similar to the data types found in the switch statement.
  4. Execution occurs when a switched variable is similar to the case.
  5. Upon execution, the switch terminates only when a break statement is reached. If there is no break, then the program continues executing up until the next line of the command after the switch statement.
  6. It is recommended that the switch statement has a default case at the end of the switch so that when none of the cases matches, there is no break until the default case.

Switch Statement Syntax

When writing switch statements, you will start by the word switch which will be followed by an expression. After the switch statement, a block with a case labels is declared so as to text for equality against the case expression. Should there be a match; the block of codes under a case label is executed before the break statement is reached.

An example of a working C++ program using case statements

We want to write a simple program that will allow you to input your grade and depending on the grade entered, it gives you the appropriate comment.

#include <iostream>
using namespace std;

int main ()
   // Declaring variables locally:
   char grade;
   cout << "Please enter your grade!\n\n:__";
   cin >> grade;

       case 'A' :
          cout << "This is an excellent Grade!\n\n";
       case 'B' :
           cout << "This Grade is not good enough but well done!\n\n";
       case 'C' :
           cout << "Nice Try\n\n";
       case 'D' :
           cout << "You passed\n\n";
       case 'F' :
           cout << "Poor performance, better try again next time\n\n";
       default :
           cout << "The grade you entered is invalid. Please enter a valid grade\n:__";
           cin >> grade;
   cout << "Your grade is\n:__" << grade ;
   cout << "\n\n";
   return 0;