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' : 
        printf("Yes"); 
        break; 
    case 'M' : 
        printf("Maybe"); 
        break; 
    case 'N' : 
        printf("No"); 
        break; 
    default: 
        printf("Invalid response"); 
}

See Also
Documentation

GNU C Manual - Switch Statement

Add to Slack

< If Statement   |   For Loop >

© 2018 SyntaxDB. All Rights Reserved.