Control Flow

Switch Case in C++

A switch case is used test variable equality for a list of values, where each value is a case. When the variable is equal to one of the cases, the statements following the case are executed. A break statement ends the switch case. The optional default case is for when the variable does not equal any of the cases.


Syntax
switch(variable) { 
    case valueOne: 
        //statements 
        break; 
    case valueTwo: 
        //statements
        break; 
    default: //optional
    //statements
}

Notes

The variable used in a switch statement can only be a short, byte, int or char. The values for each case must be the same data type as the variable type.


Example
char choice;
switch(choice) { 
    case 'Y' : 
        cout << "Yes"; 
        break; 
    case 'M' : 
        cout << "Maybe"; 
        break; 
    case 'N' : 
        cout << "No"; 
        break; 
    default: 
        cout << "Invalid response"; 
}

< If Statement   |   Ternary Operator >

© 2019 SyntaxDB. All Rights Reserved.