C++ Switch Case

The control statement that allows us to make an effective selection from a set of options is known as a switch, or a switch case-default, because these three keywords form the control statement.

Switch performs the code block that matches the case value. If the value matches none of the cases, the default block is executed.

Syntax:

switch ( integer/character expression )
{  
case {value 1} :  
do this ;
 
case {value 2} :  
 do this ;  
 
default :  
do this ;
 }

The expression after the switch can be either an integer or a character expression. Keep in mind that case labels should be unique for each case. If they are the same, it may cause an issue while running a programme. We usually use a colon at the end of the case labels ( : ). Each case is linked to a block. A block is a collection of statements that are grouped together for a specific case.

Example:

#include <iostream>
using namespace std;
 
int main()
{
    int i = 2;
    switch (i)
    {
    case 1:
        cout << "Statement 1" << endl;
        break;
 
    case 2:
        cout << "Statement 2" << endl;
        break;
 
    default:
        cout << "Default statement!" << endl;
    }
}

Output:

Statement 2
Shubhajna Rai
Shubhajna Rai

A Civil Engineering Graduate interested to share valuable information with the aspirants.

Leave a Reply

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

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in