C++ switch Statement

Introduction

The switch statement is similar to having multiple if-statements.

It checks the value of the condition (which must be integral or enum value) and, based on that value, executes the code inside one of a given set of case labels.

If none of the case statements is equal to the condition, the code inside the default label is executed.

General syntax:

switch (condition) 
{ 
case value1: /*from   w  w w  . j  a va 2 s.  c  o m*/
    statement(s); 
    break; 
case value2etc: 
    statement(s); 
    break; 
default: 
    statement(s); 
    break; 
} 

A simple example that checks for the value of integer x and executes the appropriate case label:

#include <iostream> 

int main() /*from   w  w  w. ja v a 2s . c om*/
{ 
    int x = 3; 
    switch (x) 
    { 
    case 1: 
        std::cout << "The value of x is 1."; 
        break; 
    case 2: 
        std::cout << "The value of x is 2."; 
        break; 
    case 3: 
         std::cout << "The value of x is 3."; // this statement will be   
          // executed 
        break; 
    default: 
        std::cout << "The value is none of the above."; 
        break; 
    } 
} 

The break statement exits the switch statement.

If there were no break statements, the code would fall-through to the next case statement and execute the code there regardless of the x value.

We need to put breaks in all the case: and default: switches.




PreviousNext

Related