C++ switch

In C/C++ switch is a built-in multiple-branch selection statement, which tests the value of an expression against a list of integer or character constants. When a match is found, the statements associated with that constant are executed.

Syntax

The general form of the switch statement is

snippet
switch(expression){    
case value1:    
 //code to be executed;    
 break;  
case value2:    
 //code to be executed;    
 break;  
......    
    
default:     
 //code to be executed if all cases are not matched;    
 break;  
}

When you use a series of if or if-else conditionals on the same variable, C++ code can become excessively confusing and cumbersome. Alternatively you can use switch, to test one expression for multiple values to decide which of several blocks of code to execute.

Cpp Switch 1
Example
snippet
#include <iostream>
using namespace std;
int main () {
       int num;
       cout<<"Enter a number to check grade:";  
       cin>>num;
           switch (num)  
          {  
              case 10: cout<<"It is 10"; break;  
              case 20: cout<<"It is 20"; break;  
              case 30: cout<<"It is 30"; break;  
              default: cout<<"Not 10, 20 or 30"; break;  
          }  
    }
Output
Enter a number: 10 It is 10
Output
Enter a number: 55 Not 10, 20 or 30
Note
The statements after each case label end with the break keyword to skip the rest of the switch. If the break is left out, execution will fall through to the next case, which can be useful if several cases need to be evaluated in the same way.
snippet
#include <iostream>
using namespace std;
int main () {
       int num;
       cout<<"Enter a number to check grade:";  
       cin>>num;
           switch (num)  
          {  
              case 10: 
              case 20: 
                cout<<"Value is lesser than 50";break;  
              case 100: cout<<"It is 100"; break;  
              default: cout<<"Not 10, 20 or 30"; break;  
          }  
    }

The default section handles all other values. If none of the value matches with any of the case sections it will then move to the default block.

Note
Though default is not mandatory, it’s good programming practice to have a default case in switch statements even when you don’t have a reason to employ one. The default can be used to display an error when a value and doesn’t match any of the case sections.
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +