< C Tutorial

C switch control

← Previous Next →


The Switch Statement:

The switch statement is a multi-way decision maker that tests the value of an expression against a list of constants. When  a  match is found, the statements associated with that constant are executed. The break statement ensures immediate exit from the switch statement 

Syntax:

switch(variable)
{
    case value1:
        //do operation; 
        break ; //<-- it will exit the switch block
        
    case value2:
        // do operation;
        break;
        
    .
    .
    default:
        // do operation;    
}


Example:

int main() 
{
    int id = 2 ;
    
    switch(id)
    {
        case 2:
            printf("id is 2\n");
            break ;
            
        case 14:
            printf("id is 14\n");
            break ;
            
        case 24:
            printf("id is 24\n");
            break ;
    }
    return 0;
}

Output will be:  id is 2

← Previous Next →