C++ switch statment

switch statements are also used when we need our program to make a certain decision based on a condition and then execute accordingly.

Syntax :

switch (<variable>)
{
    case a-constant-expression :
        //Code to execute if <variable> == a-constant-expression
        break;

    case b-constant-expression  :
        //Code to execute if <variable> == b-constant-expression
        break;
    .
    .
    .
    case n-constant-expression :
        //Code to execute if <variable> == n-constant-expression
        break;

    default:
        //Code to execute if <variable> does not equal the value following any of the cases
}

(We will learn about break keyword in looping statement section)
Example :

#include <iostream>
using namespace std;
int main()
{
    int input;

    cout<<"1. Play game\n";
    cout<<"2. Load game\n";
    cout<<"3. Play multi-player\n";
    cout<<"4. Exit\n";
    cout<<"Selection: ";
    cin>>input;
    cout<<"\n";

    switch ( input )
    {
        case 1: //Note the colon, not a semicolon
            cout<<"Play game called";
            break;
        case 2:
            cout<<"Load game called";
            break;
        case 3:
            cout<<"Play Multi-player game called";
            break;
        case 4:
            cout<<"Thanks for playing!\n";
            break;
        default:
            cout<<"Bad input, quitting!\n";
    }
    return 0;
}

Output :
    1. Play game
    2. Load game
    3. Play multi-player
    4. Exit
    Selection: 1
    Play game called
Important points
  • The default case is optional.
  • case constant-expression can be int or char (no other datatypes are allowed).

0 Comments