Switch-case


  • The construct switch(), which is an extension of the if. else... Statement is used for efficient multiway branching. The switch statement tests the value of the expression or variable, which is of type int or int compatible, against a list of case values and when a match is found, a block of statements associated with that case is executed.
  • The syntax is as below:
    switch (expression)
    	{
    	case value-1:	
    		block-1;
    		break;
    	case value-2:	
    		block-2;
    		break;
    	case value-3:	
    		block-3;
    		break;
    	default: 
    		default-block;
    		break;
    	}
    	statement-n;
    
  • When the switch is executed, the value of the expression is successfully compared against the values, value-1, value-2, etc.
  • If a case is found where values matches with the value of the expression, then the block of statements that follows the case is executed.
  • If there exists no match then the default block is executed. The default is optional.
  • The break statement at the end of each block indicates the end of a particular block and the execution resumes at statement-n.
  • If a break is not included in the end of each block, then all the blocks following the block executed will also be executed.
    Click here for example


Decision Statements << Previous

Next >> Goto Statement

Our aim is to provide information to the knowledge seekers. 


comments powered by Disqus
Footer1