How to Use Switch Statements in C++

When dealing with conditions in C/C++, to make comparisons and to change the flow of programs, if conditions are used but if you have to code a longer comparison or cases, too many if statements are not a good idea to use. To cope with this C and C++ provides us an alternative method to code the conditions and the comparisons, this method is called switch statement method and you can make a switch on any type of variable and then you have to write cases for that switch. I will explain the syntax and correct use of Switch statements step by step.


  • 1

    The general layout of syntax of using switch statements is described below followed by an example.
    switch (vari){
    case condition1:
    //set of statements to execute;
    case condition2:
    //set of statements to execute;
    //set of statements to execute if none of the conditions mentioned above is satisfied.

  • 2

    The switch checks the value of variable which is given as in input to the switch. Then it checks the conditions and conditions are placed on the value of variable. If a certain condition is true then the statements below that condition will execute. If none of the conditions is met then the statements below the default case will execute.

    The use of switch statements is very easy. I will write a sample code in next step, which will help you to get started with switch statements.

  • 3

    Below is the sample code to elaborate the use of switch statements. The code will check the value of an integer and then it will print the value depending on the value entered.


    using namespace std;

    int main (){

    int user_input;

    cout<<”please enter a number between 1 to 3 inclusive: ”;



    case 1:

    cout<<”you have entered 1”<


    case 2:

    cout<<”you have entered 2”<


    case 3:

    cout<<”you have entered 3”<



    cout<<”you have entered an invalid number”<



    return 0;


    I hope that this guide helps you to get going with switch statements.

    Note: the syntax of switch statements is almost same in C language.

Leave a Reply

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

− 2 = three